Setting default value for Foreign Key attribute

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

    In my case, I wanted to set the default to any existing instance of the related model. Because it's possible that the Exam with id 1 has been deleted, I've done the following:

    class Student(models.Model):
        exam_taken = models.ForeignKey("Exam", blank=True)
    
        def save(self, *args, **kwargs):
            try:
                self.exam_taken
            except:
                self.exam_taken = Exam.objects.first()
            super().save(*args, **kwargs)
    

    If exam_taken doesn't exist, django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist will be raised when a attempting to access it.

提交回复
热议问题