Setting default value for Foreign Key attribute

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

    You could use this pattern:

    class Other(models.Model):
        DEFAULT_PK=1
        name=models.CharField(max_length=1024)
    
    class FooModel(models.Model):
        other=models.ForeignKey(Other, default=Other.DEFAULT_PK)
    

    Of course you need to be sure that there is a row in the table of Other. You should use a datamigration to be sure it exists.

提交回复
热议问题