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.
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.
django rest framework - ForeignKey does not allow null values - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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.
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')
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.
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