Django Unique Together组合

时间:2019-01-11 04:32:35

标签: python django django-models

我的情况是这样的:

class Partnership(models.Model):
    partner_a = models.ForeignKey(
        "Person", 
        on_delete=models.CASCADE,
        related_name='%(class)s_partner_a',
    )
    partner_b = models.ForeignKey(
        "Person", 
        on_delete=models.CASCADE,
        related_name='%(class)s_partner_b',
    )

    class Meta:
        unique_together = (partner_a, partner_b)

如果a = a和b = b,这可以很好地拒绝重复的伙伴关系: 例如:

>>> a = Person('a')
>>> b = Person('b')
>>> Partnership.objects.create(person_a=a, person_b=b)
>>> Partnership.objects.create(person_a=a, person_b=b) # IntegretyError as expected

但是,它不能正确拒绝以下内容

>>> a = Person('a')
>>> b = Person('b')
>>> Partnership.objects.create(person_a=a, person_b=b)
>>> Partnership.objects.create(person_a=b, person_b=a) # Allowed

我是否缺少某些类别的Meta?还是有另一种方法来确保这一点? (我知道我可以覆盖保存类,但是我在问是否有一种方法可以不执行此操作。)

0 个答案:

没有答案