Setting default value for Foreign Key attribute Setting default value for Foreign Key attribute django django

Setting default value for Foreign Key attribute


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 = 1class Student(models.Model):    ...    exam_taken = models.ForeignKey("Exam", default=DEFAULT_EXAM_ID)

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


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.siglaclass City(models.Model):    nome   = models.CharField(max_length=64, unique=True)    nation = models.ForeignKey(Country, to_field='sigla', default='IT')


I use natural keys to adopt a more natural approach:

<app>/models.py

from django.db import modelsclass CountryManager(models.Manager):    """Enable fixtures using self.sigla instead of `id`"""    def get_by_natural_key(self, sigla):        return self.get(sigla=sigla)class Country(models.Model):    objects = CountryManager()    sigla   = models.CharField(max_length=5, unique=True)    def __unicode__(self):        return u'%s' % self.siglaclass City(models.Model):    nome   = models.CharField(max_length=64, unique=True)    nation = models.ForeignKey(Country, default='IT')