Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ForeignKey created empty?

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!

like image 221
Scott Avatar asked Apr 16 '10 03:04

Scott


People also ask

Can a ForeignKey be null in Django?

ForeignKey does not allow null values.

How do I create a one to many relationship in Django?

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).

Why we use ForeignKey in Django models?

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.

Are foreign keys indexed Django?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .


1 Answers

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.

like image 184
synic Avatar answered Oct 12 '22 21:10

synic