存储和检索相关模型实例中字段的默认值



我想在相关对象中存储模型实例的默认值;例如,给定以下代码:

class Contract(models.Model):
user = models.ForeignKey(User)
product = models.ForeignKey(Product)
duration = models.IntegerField(null=True, help_text='Contract validity (days)')
template = models.ForeignKey(ContractTemplate)
class ContractTemplate(models.Model):
name = models.CharField(max_length=100)
duration = models.IntegerField(help_text='Contract validity (days)')

我希望存储代表不同常见持续时间的对象,如:

yearly_contract = ContractTemplate.object.create(name='yearly', duration=365)
monthly_contract = ContractTemplate.object.create(name='monthly', duration=30)

,并在对象契约未指定值时返回链接模板的默认值:

contract1 = Contract.objects.create(user=foo_user, foo_product, template=monthly_contract)
# contract1.duration should return 365
contract2 = Contract.objects.create(user=foo_user, foo_product, duration=45, template=monthly_contract)
# contract2.duration should return 45

那么,实现这一目标的最佳方法是什么?

您可以使用一个可调用对象作为默认值。这似乎是你想要的:

请看这里:https://docs.djangoproject.com/en/3.1/ref/models/fields/默认

最新更新