Setting default value for Foreign Key attribute

后端 未结 8 735
后悔当初
后悔当初 2020-12-08 01:32

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

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 02:03

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

提交回复
热议问题