Databases and keys

Before you can understand Django models, it's important to understand databases. The type of database we use with Django most often is called a relational database.

Relational databases are made up of a series of tables. Tables are made up of columns (also called fields) and rows (also called records). Each table looks a lot like a spreadsheet. Here's an example of a table holding data about users.

user table

idusernameemailis_admin
1adminclinton@example.orgtrue
2sbrownshannon@example.orgfalse
3court9463courtney@example.orgfalse
4loganlogan.sam@example.orgfalse

Note the column called id. This column is called a primary key. It is a unique value used to identify the row. There might be other unique columns (in this case, username and email are unique), but only one primary key per table. With tables generated by Django, the primary key is always an auto-incrementing number called id.

This primary key is not only used to identify a row in a table, but also to link rows between tables. Here's an example of a table that holds photos.

photo table

iduser_idfilename
11profile.jpg
21two-cats.png
33jumanji.jpg
42bat-colony.jpg

id is similar to what you saw before: an auto-incrementing number used as the primary key. user_id is something different, though. It is a foreign key, a value which points back to a row in another table. Each of these photos was posted by a user, indicated by user_id.

  • Photo 1 was posted by the user with id 1, admin.
  • Photo 2 was also posted by the user with id 1, admin.
  • Photo 3 was posted by the user with id 3, court9463.
  • Photo 4 was posted by the user with id 2, sbrown.

This is how we store nested structures of objects in Django in two-dimensional tables, by using foreign keys to relate data across tables.

A table can have multiple foreign keys, even back to the same foreign table. Here's an example table of messages.

message table

idfrom_idto_idtextread
112Sup?true
221I'm goodfalse
331You heard from Shannon?false
434Hey, Logarithmtrue

Both from_id and to_id are foreign keys to the user table.

  • Message 1 is from admin to sbrown.
  • Message 2 is from sbrown to admin.
  • Message 3 is from court9463 to admin.
  • Message 4 is from court9463 to logan.