Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value for Foreign Key attribute

What is the best way to set a default value for a foreign key field in a model? Suppose I have two models, Student and Exam with student having exam_taken as foreign key. How would I ideally set a default value for it? Here's a log of my effort

class Student(models.Model):    ....    .....    exam_taken = models.ForeignKey("Exam", default=1) 

Works, but have a hunch there's a better way.

def get_exam():     return Exam.objects.get(id=1)  class Student(models.Model):     ....     .....     exam_taken = models.ForeignKey("Exam", default=get_exam) 

But this fails with tables does not exist error while syncing.

Any help would be appreciated.

like image 706
Primal Pappachan Avatar asked Feb 16 '12 13:02

Primal Pappachan


People also ask

Can a foreign key have a default value?

Yes, you can define a column with a default value of 0 as a Foreign Key. However, for the constraint to work, you would need to have a row in the source table with a value of 0 as well.

Can a foreign key be null Django?

django rest framework - ForeignKey does not allow null values - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

How are foreign keys used in models?

To define a relationship between two models, you need to define the ForeignKey field in the model from the Many side of the relationship. In other words, ForeignKey should be placed in the Child table, referencing the Parent table.


2 Answers

I would modify @vault's answer above slightly (this may be a new feature). It is definitely desirable to refer to the field by a natural name. However instead of overriding the Manager I would simply use the to_field param of ForeignKey:

class Country(models.Model):     sigla   = models.CharField(max_length=5, unique=True)      def __unicode__(self):         return u'%s' % self.sigla  class City(models.Model):     nome   = models.CharField(max_length=64, unique=True)     nation = models.ForeignKey(Country, to_field='sigla', default='IT') 
like image 33
Carson McNeil Avatar answered Sep 28 '22 05:09

Carson McNeil


In both of your examples, you're hard-coding the id of the default instance. If that's inevitable, I'd just set a constant.

DEFAULT_EXAM_ID = 1 class Student(models.Model):     ...     exam_taken = models.ForeignKey("Exam", default=DEFAULT_EXAM_ID) 

Less code, and naming the constant makes it more readable.

like image 143
Gareth Avatar answered Sep 28 '22 04:09

Gareth