Django Model Fields

By: Dusty Arlia
Published on Tuesday, March 4, 2014, 07:31 PM
Last Updated on Tuesday, July 07, 2015 at 10:28 PM
Total Updates: 5

Django model fields are just class attributes of your model. All model fields in Django are subclasses of django.db.models.Field. Django keeps track of certain features of fields:

  • Field name
  • Field help text
  • The uniqueness of the field

All of this information is handled by the Field class. The field classes you define in a model are actually stored in the Meta class when the model class is created. This is because the field classes aren’t necessary when you’re just creating and modifying attributes. They can convert the attribute value to what is stored in the database or sent to the serializer.

The only required part of a Django model is the list of database fields it defines. Fields are defined by class attributes. Do not choose field names that conflict with the models API (e.g. clean, save, or delete).

Here is an example:

from django.db import models

class Faculty(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class Class(models.Model):
    teacher = models.ForeignKey(Faculty)
    class_name = models.CharField(max_length=100)

Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine these things:

  • The database column type (e.g. INTEGER, VARCHAR)
  • The default HTML widget to use when rendering a form field (e.g. <input type="text">, <select>)
  • The minimal validation requirements, used in Django’s admin and in automatically-generated forms

Django comes with dozens of built-in field types. You can write your own field type if Django’s built-in ones don’t fill your data requirements. In Django, these are called custom model fields.