Django Model 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.
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.
- The default HTML widget to use when rendering a form field (e.g.
- 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.