我正在使用Django 1.5并且正在努力解决我认为非常基本的问题。
我有以下人物模型:
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(“名称'Person'未定义”):
partner = models.OneToOneField(Person, blank=true, null=true)
有人能指出我正确的方向吗?
答案 0 :(得分:3)
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()
答案 1 :(得分:3)
试试这个:
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)