2

我正在使用 Django 1.5,并且正在努力解决我认为非常基本的问题。

我有以下 Persons 模型:

class Person(models.Model):
    contact_person = models.ManyToManyField(ContactPerson)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
...

目标是将人的合作伙伴添加到模型中。我不希望对方或对方比对方优越;他们应该是平等的。换句话说,在查找一个人时,他/她的伴侣也应该出现(如果有的话)。我需要能够添加一次合作伙伴,无论是在女方还是在男方(我不想将它们链接两次)。

我已经搜索了 OneToOneFields 的文档,但似乎不支持递归 OneToOnes,即当我尝试时出现 NameError ("name 'Person' is not defined"):

partner = models.OneToOneField(Person, blank=true, null=true)

谁能指出我正确的方向?

4

2 回答 2

4

Try this:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    ...
    partner = models.OneToOneField('self', null=True, blank=True)

    def save(self, checkPartner = True, *args, **kwargs):
        super(Person, self).save()
        if self.partner and checkPartner:
            self.partner.partner = self
            self.partner.save(checkPartner = False)
  • Null true on partner field, has to be enabled because the first person to be saved will not have any partner.
  • checkPartner parameter has been added so that save() doesn't fall into an infinite loop
于 2013-08-16T12:24:22.937 回答
4

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

partner = models.OneToOneField('Person', blank=true, null=true)

或者,如果你在同一个班级

partner = models.OneToOneField('self', blank=true, null=true)

引号就是一切,在这种情况下

def save(self, *args, **kwargs):
    # call to super, we want self.partner to be set
    super(Person, self).save(*args, **kwargs)

    # this is necessary to avoid infinite save loops on partner's save call
    # at this point, you have a partner
    # this won't work if your partner has already a partner
    # but it's easy to go from here
    if not self.partner.partner:
        self.partner.partner = self
        self.partner.save()
于 2013-08-16T10:22:40.353 回答