liveBook · Manning

Model field

As explained in Django in Action

A Django model field defines a model attribute together with its database storage, validation, and related behavior.

A Django model field describes one model attribute and the database column behind it. It also determines how Django represents, validates, and works with that value. Defining fields declaratively lets a Model class describe the table structure that Django manages. section 4.12 section 4.4 section 4.8

Use fields to control several parts of model behavior:

  • Choose a data type, such as CharField for Python strings or DateField for Python date objects. section 4.4
  • Configure the underlying column with arguments such as max_length; available arguments vary by field. section 4.8
  • Add framework behavior beyond a raw SQL type, as EmailField does by validating email-shaped text. section 4.8
  • Connect models through relationship fields, including ForeignKey and ManyToManyField. section 4.12

Fields on a musician model

A Musician model can define first_name and last_name as CharField attributes and birth as a DateField. Creating an object then uses those field names as keyword arguments: Musician.objects.create(first_name="Steve", last_name="Vai", birth=date(1960, 6, 6)). Django returns a Musician whose attributes use ordinary Python values. If the model changes, makemigrations records the required database change and migrate applies it. section 4.4 section 4.12

(venv) RiffMates$ python manage.py shell
Python 3.12.1
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from bands.models import Musician
>>> from datetime import date
>>> steve = Musician.objects.create(first_name="Steve",
 last_name="Vai", birth=date(1960, 6, 6)) #1

Try creating a Musician in the Django shell to see field names become keyword arguments and database data become a model object. section 4.4

How Django in Action covers it

How deep it goes
Explains type mapping, arguments, validation, relationships, and migrations, but defers the complete field reference.
Examples
Uses Musician names and birth dates, EmailField validation, relationship fields, and interactive object creation.
What it assumes
Assumes basic Python classes and values while teaching database structure through Django models and declarative fields.
What you can do after
Build it from scratch by defining typed model attributes, configuring arguments, creating objects, and applying schema changes.
How it connects
Connects model fields with Django models, the Django ORM, database columns, validation, migrations, and ModelForm.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.