When writing code we are attempting to model real-world things - this may be a blog, a process, a series of things. For example, if we are writting a blog the most basic question is:
What is the least amount of information we need in order to create a new, empty blog?
The answer here might be a title and a description. Other attributes, like authorship may be handy, as posts.
More documentation at docs.
Where to write models?
Django has the concept of apps - parts of a larger project that serve a specific purpose that is part of the overall project. For example, having user accounts can be handled by an app dedicated to that purpose.
Models, then, can be distributed across their specific “apps”. In writing a blog, for instance, we create an “app” called blogs, which is another way of saying “a work folder called blogs.
We can begin by simply creating a root-level folder called blogs, which will contain a models.py file:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.titleMuch of the code that manages a model within the context of a larger project is built-in into the models.Model class.
To inform Django about apps we have installed we have to update settings.py. Specifically, we include a list called INSTALLED_APPS with the name of each folder in the Django project.
Additionally, we want to include a DATABASES dictionary to include specific database information:
# settings.py
...
INSTALLED_APPS = ["blogs"]
DATABASES = {
"default" : {
"ENGINE" : "django.db.backends.sqlite3",
"NAME" : Path(__file__).parent / "db.sqlite3",
}
}
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
Modelling data
Registering models
After we have a model we have to register it with Django; in other words, we need to make sure Django knows where to find it and what path to use.
For example, after we set up the Django Admin configuration, we have to register the app in our main application file, and if we wrote any specific model we also have to import it into our app:
# app.py
from django.contrib import admin
from blogs.models import Blog
admin.site.register(Blog)
...
urlpatterns = [
path("admin/", admin.site.urls)
]Note
admin.site.registeraccepts either a single model or a sequence of models (just as a list or tuple)
Note
Registering the model to admin with
admin.site.register(<model>)allows Django admin to manage the specific model.
Note
It is also possible to register models with a model with the regsiter()decorator.
Caution
The trailing
/in theadminpath is significant. If it is included,localhost:8000/admin(without trailing slash) will not match.