🎓 A1Learner
🔍
0 of 50 lessons completed

Django Model Fields

A model field is one column of a model's table. Each field sets the kind of value that column holds.

A post with four fields

The Post model has four fields. Each field sets one kind of value.

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    views = models.IntegerField()
    published = models.BooleanField()

    class Meta:
        app_label = "blog"

Read the field values

The post holds one value per field. The prints show three of them.

post = Post(title="First post", body="Hello from Django.", views=7, published=True)
print(post.title)
print(post.views)
print(post.published)

A starting value

A field can name its own starting value. A new draft starts at zero views.

class Draft(models.Model):
    title = models.CharField(max_length=100)
    views = models.IntegerField(default=0)

    class Meta:
        app_label = "blog"

draft = Draft()
print(draft.views)

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=[
        "django.contrib.contenttypes",
        "django.contrib.auth",
    ],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django.db import connection, models

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    views = models.IntegerField()
    published = models.BooleanField()

    class Meta:
        app_label = "blog"

with connection.schema_editor() as editor:
    editor.create_model(Post)

post = Post(title="First post", body="Hello from Django.", views=7, published=True)
print(post.title)
print(post.views)
print(post.published)

Key points

  • A column holds one kind of value across all rows.
  • Use CharField for short text, with a max_length.
  • Use TextField for long text, with no length limit.
  • Use IntegerField for whole numbers.
  • Use BooleanField for a true or false value.
  • The field name becomes the column name.

In this example, the setup lines configure Django. The Post class has four fields for four kinds of values. The program creates the table directly. A real project uses migrations for this step. The last lines make one post and print its title, views, and published values.

Note

A CharField needs max_length. A TextField does not.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which field holds short text with a length limit?