Django
Django Models
Database models
Django Models
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table.
Define a Model
Models are defined in models.py:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.IntegerField()
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
Field Types
Django provides many field types:
CharField- For stringsIntegerField- For integersTextField- For large textEmailField- For email addressesDateField- For datesDateTimeField- For date and timeBooleanField- For true/false
Create Migrations
After defining models, create migrations:
python manage.py makemigrations
Apply Migrations
Apply migrations to the database:
python manage.py migrate
Using Models
You can use models in your views:
from .models import Person
def index(request):
people = Person.objects.all()
return render(request, 'myapp/index.html', {'people': people})
Model Methods
Add methods to your models:
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __str__(self):
return f"{self.first_name} {self.last_name}"
def get_full_name(self):
return f"{self.first_name} {self.last_name}"