我有一个带有两个外键字段的django模型,一个指向产品,另一个指向下面代码中的产品组合.Exatcly应为每个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
小智.. 8
您可以覆盖模型的save
方法:
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
.