This seems very basic and I must be missing something, but here goes anyways...
With two models like so:
class School(models.Model):
name = models.CharField("Official School Name", max_length=128)
address = models.TextField("Address of the School", max_length=256)
mascot = models.CharField("Name of the School Mascot", max_length=128)
class StudentProfile(models.Model):
name = models.CharField(max_length=128)
school = models.ForeignKey(School)
If the student gets created before the school, how do I give 'school' a default empty value? Is it blank or null or what?
Thanks!
ForeignKey does not allow null values.
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
null
if you want the database to allow the relationship to be null, blank
if you don't want the Django admin site to complain about it being null.
From the documentation on "blank":
"Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, validation on Django’s admin site will allow entry of an empty value. If a field has blank=False, the field will be required."
In short, you probably want both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With