Welcome back to CodeYourCraft! Today, we're diving into one of the most crucial aspects of Django - Models and Relationships. By the end of this tutorial, you'll be equipped with the knowledge to manage data in your Django applications effectively. π
In simple terms, a Model in Django is a representation of a database table. It defines the structure of the table, including the field types, names, and their attributes. Models help us create, read, update, and delete (CRUD) records in our database.
Let's create a simple Model for a Book entity. In your project's apps directory, navigate to your app's models.py file and add the following code:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publication_year = models.IntegerField()Here, we've defined a Book Model with three fields: title, author, and publication_year.
Now, let's create the database table for our Model using Django's migration system:
python manage.py makemigrations
python manage.py migrateDjango offers a variety of field types to suit your data needs. Here are some common ones:
CharField: for storing strings, like book titlesIntegerField: for whole numbers, like publication yearsFloatField: for decimal numbers, like ratingsBooleanField: for true/false values, like whether a book is availableIn real-world applications, data is often interconnected. For example, a Book might have multiple Authors, and an Author might write multiple Books. These interconnections are known as relationships.
In Django, we can define relationships using ForeignKey, ManyToManyField, and OneToOneField. Let's modify our Book Model to include an Author relationship:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey('Author', on_delete=models.CASCADE)
publication_year = models.IntegerField()Here, we've added a ForeignKey relationship with the Author Model.
Let's create an Author Model:
class Author(models.Model):
name = models.CharField(max_length=100)After creating the Model and migrating the database, you can create an Author instance and assign it to a Book instance:
author1 = Author.objects.create(name='John Doe')
book1 = Book.objects.create(title='The Catcher in the Rye', author=author1, publication_year=1951)By using Django's relationship fields, you can build complex data models that reflect the real-world connections between entities. For example, a Book might have multiple Chapters, and each Chapter might have multiple Sections.
What does a Model represent in Django?
Stay tuned for our next tutorial, where we'll delve deeper into Django's view system and learn how to create dynamic web pages based on our Models! π