我有一个带有两个外键字段的 Django 模型,一个指向产品,另一个指向下面代码中的投资组合。应该为每个 Lca 记录设置其中一个。我知道我可以用 MySQL 触发器来做到这一点,但我想知道是否有办法在 django 中进行这种有条件的保存
class Lca(models.Model):
product = models.ForeignKey(product, null=True, blank=True)
portfolio = models.ForeignKey(portfolio, null=True, blank=True)
carbon_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
name = models.CharField(max_length=255, blank=True)
total_footprint = models.IntegerField(blank=True, null=True)
calculation_type = models.CharField(max_length=9)
total_cv = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True)
source = models.CharField(max_length=255, blank=True)
date_from = models.DateField()
date_to = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.name
# end __unicode__
# end
最佳答案
def save(self, *args, **kwargs):
if self.product and self.portfolio or not self.product and not self.portfolio:
raise ValueError('Exactly one of [Lca.product, Lca.portfolio] must be set')
super(Lca, self).save(*args, **kwargs)
注意此方法不适用于bulk_create
.
关于mysql - 两个外键字段,恰好一个被设置为一个值,另一个在MySQL数据库的django模型中为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20491037/