Setting default value for Foreign Key attribute

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

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

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

    0 讨论(0)
  • 2020-12-08 02:22

    I use natural keys to adopt a more natural approach:

    <app>/models.py

    from django.db import models
    
    class 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.sigla
    
    class City(models.Model):
        nome   = models.CharField(max_length=64, unique=True)
        nation = models.ForeignKey(Country, default='IT')
    
    0 讨论(0)
提交回复
热议问题