Setting default value for Foreign Key attribute

后端 未结 8 739
后悔当初
后悔当初 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

    the best way I know is to use lambdas

    class TblSearchCase(models.Model):
        weights = models.ForeignKey('TblSearchWeights', models.DO_NOTHING, default=lambda: TblSearchWeights.objects.get(weight_name='value_you_want'))
    

    so you can specify the default row..

    default=lambda: TblSearchWeights.objects.get(weight_name='value_you_want')
    

提交回复
热议问题