Django: Getting Started Transcripts
Chapter: Django ORM and Databases
Lecture: Creating the Book model

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Alright, you can store an author let's add a book class. Unlike the CharField, the text field is unlimited.
0:11 It tends to be less performant in the database. I could argue that this should also be a CharField but then you'd not be seeing a text field in use.
0:23 This is your first relationship field. By default, every model has an identifer named ID
0:28 And Django sets this automatically as the primary key for the table. A primary key is an identify their unique to a table.
0:37 That can be used to specify relationships between objects. A foreign key is just the primary key of an object in a different table.
0:47 In this case, the author field on the book model will contain the primary key of a row in the author table.
0:55 Thus denoting the relationship between this book and that author. The foreign key field has a couple of required parameters,
1:04 the first of which is something that specifies what object this book is related to. That's the author class.
1:11 This can be specified either as a class or as a string containing the name of a class.
1:16 The string can help you get around having to define your classes in a certain order
1:21 The on delete argument instructs the database on what to do with this object. If the foreign key is deleted,
1:28 setting this option to cascade indicates that if the author is deleted, you should also automatically delete the corresponding books.
1:37 Other options let you leave the book intact but to wipe out the value of the author key, it's up to you which you want to do.
1:45 The options to the foreign key also have another use of that blank thing I was talking about before.
1:52 In this case, specifying that informs this field can be empty unlike a string which has the option of being an empty string,
2:00 the only way to leave a key empty is with the null indicator. That's why you have both the blank and null arguments to this class
2:08 The null is enforced by the database and the blank is enforced by Django. This can be a bit confusing at first,
2:16 but you want to be careful to set them correctly. Otherwise you might end up with the database rejecting the field having no contents even though
2:24 the Django admin says it can be blank.


Talk Python's Mastodon Michael Kennedy's Mastodon