Django Models are the building blocks for your database in Django. They define the structure of your database tables and provide a way to interact with the data.
Overview
- Django ORM: Django uses an Object-Relational Mapping (ORM) system to interact with the database. This allows you to work with Python objects instead of raw SQL queries.
- Model Classes: Each model corresponds to a database table. You define a model by creating a Python class that inherits from
django.db.models.Model
. - Fields: Each model has fields that define the columns of the table. Common fields include
CharField
,IntegerField
,DateTimeField
, and more.
Basic Usage
Here's a simple example of a Django model:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.CASCADE)
published_date = models.DateTimeField(auto_now_add=True)
content = models.TextField()
def __str__(self):
return self.title
Fields
Django provides a variety of field types to suit different data needs. Here are some common fields:
- CharField: For text fields with a fixed length.
- TextField: For text fields with an arbitrary length.
- IntegerField: For whole numbers.
- FloatField: For floating-point numbers.
- DateTimeField: For date and time data.
Relationships
Django supports various types of relationships between models, such as:
- One-to-One: A single instance of one model relates to a single instance of another model.
- One-to-Many: A single instance of one model can relate to multiple instances of another model.
- Many-to-Many: Multiple instances of one model can relate to multiple instances of another model.
For example, to create a one-to-many relationship between Article
and Author
, you can define it like this:
class Author(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateTimeField(auto_now_add=True)
content = models.TextField()
def __str__(self):
return self.title
Further Reading
For more detailed information on Django Models, please visit the Django Documentation.