Text and Number Fields
Django gives you a rich set of field types to match your data. Let's start with the basics โ text and numbers.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField(default=0)
rating = models.FloatField(null=True, blank=True)
CharField requires a max_length. TextField has no limit. DecimalField is perfect for money โ never use FloatField for prices because of rounding issues.
Date and Time Fields
Handling dates and times is a breeze with Django. There are three main options depending on your needs.
class Event(models.Model):
name = models.CharField(max_length=200)
date = models.DateField()
time = models.TimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
Use DateField for just dates, TimeField for just times, and DateTimeField for both. The auto_now_add and auto_now parameters handle timestamps automatically.
Specialized Fields
Django includes fields for common data types you'll encounter in real projects.
class UserProfile(models.Model):
email = models.EmailField()
website = models.URLField()
avatar = models.ImageField(upload_to='avatars/')
resume = models.FileField(upload_to='documents/')
is_active = models.BooleanField(default=True)
EmailField validates email format. URLField validates URLs. ImageField and FileField handle uploads โ just make sure you've configured MEDIA_ROOT in settings.
Relationship Fields
Real-world data is connected. Django provides three field types for relationships between models.
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class Library(models.Model):
name = models.CharField(max_length=200)
books = models.ManyToManyField(Book)
class Profile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
bio = models.TextField()
ForeignKey creates a many-to-one relationship. ManyToManyField creates many-to-many. OneToOneField creates a strict one-to-one link. The on_delete parameter is mandatory for ForeignKey and OneToOneField โ it tells Django what to do when the related object is deleted.