我已经建立了这个模型(想象的链接不止E_HUSBAND_WIFE
):
class EntityLink(models.Model):
E_HUSBAND_WIFE = 1
TAB_TYPES = {
E_HUSBAND_WIFE: {'src': _("is the husband of"),
'dst': _("is the wife of"), },
}
link_type = models.IntegerField(
choices=[(a, f'{b["src"]} ↔ {b["dst"]}') for a, b in TAB_TYPES.items()],
default=None, blank=True, null=True)
src = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='src')
dst = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='dst')
class Meta:
# you cant have same relation between two entities twice:
unique_together = ('src', 'dst', 'link_type')
src
和一个dst
,我只能拥有一种关系。src
和同一dst
之间可以有多个关系。例如,一个src
可以是dst
的丈夫,但他也可以是teacher
(代码中未显示)。例如:
src
= Garry
,dst
= Rose
,link_type
= E_HUSBAND_WIFE
src
= Garry
,dst
= Rose
,link_type
= E_HUSBAND_WIFE
。好!但是有一个问题:仅凭这些规则,您仍然可以添加新记录:
src
= Rose
,dst
= Garry
,link_type
= E_HUSBAND_WIFE
我要禁止这个!在插入/更新之前,如果(src, dst, link
已经以(dst, src, link
)的形式出现,我需要禁止这样做。
该怎么做?