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
