When creating a model, the first question we have to ask is:
Question
What is the simplest way we can represent the data?
For example, if we are creating a blog and we are trying to models blog posts we might say that it needs a title, a body, and possible an author.
Using Django
To create a Django Data Model that represents a blog post we can include the following into models.py:
# models.py
from django.db import models
class Blog(models.Model):
...
class BlogPost(models.Model):
title = models.CharField(max_length=500)
body = models.TextField()
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title[:50]The most important line of the BlogPost model is the ForeignKey, which establishes a connection to the Blog model. In other words, the blog variable in BlogPost is a foreign key that points to a specific instance of Blog.
The on_delete=models.CASCADE option establishes that if the Blog is deleted, all the instances of BlogPost associated with that Blog will also be deleted.
Once the model has been written, the migrations crated, and the migrations run, make sure to register the model with the admin site.