A Django model is a Python class that describes data resources. In the vast majority of cases, this will be a relational database such as MySQL or Postgres.
A model provides two interlinked pieces of functionality. They provide a way of describing a database, its tables and the relationships between those tables in pure Python code.
We can then use this Python code so your web application can access the data in a logical and understandable fashion in what’s called object-relational mapping.
This example model creates a new Python class which creates a database table. It defines a Person, which has a first_name and last_name:
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.name
first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
You don’t have to declare the Primary Key in the model.
The last part of the model is a method (function in a class) which returns the name of the row.
Another class we could create, which links to the first class using a ForeignKey field:
class Address(models.Model): number = models.IntegerField(null=False, blank=True) street_name = models.CharField(max_length=500, null=False, blank=True) resident = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL)
We’re now in a position that we could use our models within the views that we already have.
If we jumped back to the views.py, simple view to start using our new database about people and their addresses.
Let’s look at a simple view, perhaps we just want to see the information about the first address.
First of all, we’ll create a variable that contains only addresses we know about. We reference the address table, we want the object, and we want every object. We’re only interested in the first address, and in this instance the all method returns a Python list. We can get the first address with the simple pipeline list indexing.
So in views.py add this:
def simple_view(request): addresses = Address.object.all() first_address = address resident_name = str(first_address.resident) html = "<html><head></head><body>Name: "+resident_name+"<br />Address:"+
first_address.street_name+"</body></html>" return HttpResponse(html)
So – the model classes describe database tables, and the class variables describe the columns in that database.
Within our views, then we can use various data retrieval functions to get the data back. We can subset it the way that we want, and then we can access the data that’s in each row of the table one at a time using the class variable names.