我希望 ForeignKey 的每个实例都有不同的默认值,具体取决于它在父模型中的属性。
一个插图可能会更清楚地说明这一点:
class Day(models.Model):
date = models.DateField(unique=True)
manager_shift = models.ForeignKey('Shift') # Shift.shift_type should be "M"
lead_shift = models.ForeignKey('Shift') # Shift.shift_type should be "L"
early_day_shift = models.ForeignKey('Shift') # Shift.shift_type should be "ED"
late_day_shift = models.ForeignKey('Shift') # Shift.shift_type should be "LD"
swing_shift = models.ForeignKey('Shift') # Shift.shift_type should be "SW"
early_evening_shift = models.ForeignKey('Shift') # Shift.shift_type should be "EM"
late_evening_shift = models.ForeignKey('Shift') # Shift.shift_type should be "LM"
class Shift(models.Model):
user = models.ForeignKey('User', limit_choices_to={'is_staff': True}, blank=False)
shift_type = models.CharField(max_length=2, choices=SHIFT_TYPE_CHOICES, blank=False)
SHIFT_TYPE_CHOICES = {
('M', 'Manager'),
('L', 'Lead'),
('ED', 'Early Day'),
('LD', 'Early Day'),
('SW', 'Swing'),
('EM', 'Early Evening'),
('LM', 'Late Evening'),
}
在这种情况下,
所以在做的时候:
Day.manager_shift = Shift()
Day.manager_shift.shift_type 应该自动为“M”