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
id | username | is_admin | |
---|---|---|---|
1 | admin | clinton@example.org | true |
2 | sbrown | shannon@example.org | false |
3 | court9463 | courtney@example.org | false |
4 | logan | logan.sam@example.org | false |
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
id | user_id | filename |
---|---|---|
1 | 1 | profile.jpg |
2 | 1 | two-cats.png |
3 | 3 | jumanji.jpg |
4 | 2 | bat-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
id | from_id | to_id | text | read |
---|---|---|---|---|
1 | 1 | 2 | Sup? | true |
2 | 2 | 1 | I'm good | false |
3 | 3 | 1 | You heard from Shannon? | false |
4 | 3 | 4 | Hey, Logarithm | true |
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.