两个外键字段,正好一个设置为一个值,另一个在带有MySQL数据库的django模型中为null

Mag*_*AMP 5 mysql django conditional foreign-keys

我有一个带有两个外键字段的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
Run Code Online (Sandbox Code Playgroud)

小智 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)
Run Code Online (Sandbox Code Playgroud)

请注意,此方法不适用于bulk_create.