Models
Django models are used to define the structure of the data in a Django application. They are defined in the models.py
file of an app and are used to create the database tables that store the data for the app.
How to create models
- Open the
models.py
file in the app directory. - Import the
models
module fromdjango.db
:
from django.db import models
- Create a new class that inherits from
models.Model
. This class will define the fields and properties of the model. Define the fields of the model using the various field classes provided by Django. For example:
class Club(models.Model):
name = models.CharField(max_length=255)
country = models.CharField(max_length=255)
division = models.CharField(max_length=255)
date_of_creation = models.DateField()
- Add any methods to the model class that are required for the app's functionality.
class Manager(models.Model):
name = models.CharField(max_length=255)
country = models.CharField(max_length=255)
no_of_titles = models.IntegerField(default=0)
date_of_birth = models.DateField()
def __str__(self):
return f"{name}"
@classmethod
create_manager(cls, name, country, no_of_titles, date_of_birth):
manager = None
try:
manager = cls.objects.create(
name = name,
country = country,
no_of_titles = no_of_titles,
date_of_birth = date_of_birth,
)
except Exception as e:
print(f'there was an exception:\n {e}')
return manager
class Club(models.Model):
name = models.CharField(max_length=255)
country = models.CharField(max_length=255)
division = models.CharField(max_length=255)
date_of_creation = models.DateField()
def __str__(self):
return f"{name}"
@classmethod
create_club(cls, name, country, division, date_of_creation):
club = None
try:
club = cls.objects.create(
name = name,
country = country,
division = division,
date_of_creation = date_of_creation,
)
except Exception as e:
print(f'there was an exception:\n {e}')
return club
- Run migrations to create the database tables for the models:
python manage.py makemigrations
python manage.py migrate
Now you can use the model to create, retrieve, update, and delete records in the database using the Django ORM.
Note that there are many other types of fields available in Django models, such as IntegerField, TextField, DateTimeField, and so on. You can also add properties like ForeignKey, ManyToManyField, etc to define relationships between tables. You can find more information on the available fields and properties in the Django documentation.
Querying models
Django models provide a convenient way to interact with your database using Python code. One of the most common tasks when working with models is querying the database to retrieve specific data.
Here are a few examples of common model queries in Django:
Retrieving all objects:
To retrieve all objects from a model, you can use the objects.all()
method. For example, if you have a model named Club
(as shown above), you can retrieve all clubs by calling Club.objects.all()
.
Club.objects.all()
#Returns a queryset of Club Objects
Filtering objects:
To retrieve specific objects from a model based on certain conditions, you can use the objects.filter()
method. For example, if you want to retrieve all clubs where the date_of_creation
is greater than a certain date, you can use the following query:
Club.objects.filter(date_of_creation__gt='1982-01-01')
Retrieving a single object:
To retrieve a single object from a model, you can use the objects.get()
method. For example, if you want to retrieve an club with a specific id, you can use the following query:
Club.objects.get(id=1)
Ordering objects:
To order the objects returned from a query, you can use the order_by()
method. For example, if you want to retrieve all clubs sorted by date_of_creation
, you can use the following query:
Club.objects.all().order_by('date_of_creation')
Chain multiple query conditions:
You can chain multiple query conditions to filter the results. For example, to retrieve all clubs that were created after 2002 and their manager is "Klopp":
Club.objects.filter(date_of_creation__gt='2002-01-01', manager__name='Klopp')
These are just a few examples of the many querying options available in Django's ORM. The official Django documentation provides more information on querying models and other ORM features.