Fields and Meta

What this is. A model is a class. Django turns it into a table: one class, one table; one attribute, one column.

You describe the data in Python and never write CREATE TABLE.

Field choices are decisions, not formalities.

CharField needs max_length and is for short text. TextField does not and is for long text.

BooleanField(default=False) — give it a default, or existing rows have no answer.

DateTimeField(auto_now_add=True) is set once, at creation. auto_now=True updates on every save. Mixing them up gives you a 'created' date that changes every time someone edits.

Two methods worth writing every time.

__str__ returns something readable. Without it the admin and the shell show Post object (1) for everything, which makes both nearly useless.

Meta.ordering gives a default order. Without one, the database returns rows in whatever order it likes, and it is allowed to change its mind.

◈ Graded Challenge

Write a Post class in plain Python that behaves the way a Django model would. The constructor takes a title and an optional body defaulting to an empty string. It sets published to False. __str__ returns the title. A publish() method sets published to True and returns the object. A summary() method returns the first 20 characters of the body followed by an ellipsis character when the body is longer than 20 characters, and the whole body otherwise.

Name it exactly: class Post

Python4 visible + 4 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Relationships →
← Back