Django model fields

Prerequisites

Django Model Fields

  • One of the core features of Django is the Object-Relational Mapping (ORM), which allows developers to interact with databases using Python code instead of SQL.
  • At the heart of Django’s ORM are model fields, which define the data types and constraints for your database tables.
  • Model fields in Django are attributes of a model class that map to database table columns.
  • Each field corresponds to a specific type of data that a column will store, such as strings, numbers, dates, or binary data.

Commonly Used Model Fields

Django provides a variety of fields to handle different data types and constraints:

1. String Fields

These fields are used to store text data.

  • CharField: Stores short-to-moderate length strings. Requires a max_length argument.
    title = models.CharField(max_length=200)
    
  • TextField: Stores long text without a max_length limit.
    description = models.TextField()
    

2. Numeric Fields

For storing numbers, Django provides the following fields:

  • IntegerField: Stores whole numbers.
    quantity = models.IntegerField()
    
  • DecimalField: Stores decimal numbers with fixed precision. Requires max_digits (total digits) and decimal_places.
    price = models.DecimalField(max_digits=8, decimal_places=2)
    
  • FloatField: Stores floating-point numbers.
    rating = models.FloatField()
    

3. Boolean Fields

  • BooleanField: Stores True or False.
    is_active = models.BooleanField(default=False)
    

4. Date and Time Fields

  • DateField: Stores dates (e.g., 2024-11-20).
    start_date = models.DateField()
    
  • TimeField: Stores time (e.g., 14:30:00).
    start_time = models.TimeField()
    
  • DateTimeField: Stores both date and time.
    event_time = models.DateTimeField()
    

5. Relational Fields

These fields establish relationships between models:

  • ForeignKey: Represents a one-to-many relationship.
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    
  • OneToOneField: Represents a one-to-one relationship.
    profile = models.OneToOneField(User, on_delete=models.CASCADE)
    
  • ManyToManyField: Represents a many-to-many relationship.
    tags = models.ManyToManyField(Tag)
    

6. File and Image Fields

These fields store file and image data:

  • FileField: For uploading files.
    document = models.FileField(upload_to='documents/')
    
  • ImageField: For uploading images (requires Pillow library).
    photo = models.ImageField(upload_to='images/')
    

7. Specialized Fields

  • EmailField: Validates email addresses.
    email = models.EmailField()
    
  • URLField: Validates URLs.
    website = models.URLField()
    
  • SlugField: Stores short labels for URLs.
    slug = models.SlugField(unique=True)
    
  • UUIDField: Stores universally unique identifiers.
    identifier = models.UUIDField(default=uuid.uuid4, editable=False)
    

Field Options and Attributes

Each field in Django can accept several options that define its behavior. Here are some commonly used attributes:

  • null: If True, allows NULL values in the database. Default is False.
    middle_name = models.CharField(max_length=50, null=True)
    
  • blank: If True, allows empty values in forms. Default is False.
    nickname = models.CharField(max_length=50, blank=True)
    
  • default: Sets a default value for the field.
    is_published = models.BooleanField(default=False)
    
  • unique: If True, ensures unique values in the database.
    email = models.EmailField(unique=True)
    
  • choices: Defines a fixed set of values for the field.
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('published', 'Published'),
    ]
    status = models.CharField(max_length=10, choices=STATUS_CHOICES)
    
  • verbose_name: A human-readable name for the field.
    created_at = models.DateTimeField(verbose_name='Creation Date')
    

Custom Fields

If Django’s built-in fields don’t meet your requirements, you can create custom fields by subclassing models.Field. For example:

from django.db import models

class UpperCaseCharField(models.CharField):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get_prep_value(self, value):
        return str(value).upper()

This custom field converts all input values to uppercase before saving them to the database.

References: