如何查询ManyToManyField

时间:2013-08-17 08:02:04

标签: django django-models django-orm

我在帖子上看到了这个模型。

models.py:

class Person(models.Model):
    name = models.CharField(max_length=100)
    relationships = models.ManyToManyField('self', through='Relationship', 
                                           symmetrical=False, 
                                           related_name='related_to')

    def __unicode__(self):
        return self.name

RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
    (RELATIONSHIP_FOLLOWING, 'Following'),
    (RELATIONSHIP_BLOCKED, 'Blocked'),
)

class Relationship(models.Model):
    from_person = models.ForeignKey(Person, related_name='from_people')
    to_person = models.ForeignKey(Person, related_name='to_people')
    status = models.IntegerField(choices=RELATIONSHIP_STATUSES)

    def __unicode__(self):
        return "%s %s %s" % (self.from_person, self.status, self.to_person)

    def add_relationship(self, person, status):
        relationship, created = Relationship.objects.get_or_create(
            from_person=self,
            to_person=person,
            status=status)
        return relationship

    def remove_relationship(self, person, status):
        Relationship.objects.filter(
            from_person=self, 
            to_person=person,
            status=status).delete()
        return

    def get_relationships(self, status):
        return self.relationships.filter(
            to_people__status=status, 
            to_people__from_person=self)

    def get_related_to(self, status):
        return self.related_to.filter(
            from_people__status=status, 
            from_people__to_person=self)

    def get_following(self):
        return self.get_relationships(RELATIONSHIP_FOLLOWING)

    def get_followers(self):
        return self.get_related_to(RELATIONSHIP_FOLLOWING)

如何让这个人关注的人或跟随此人的人?我试过这样做:

>>>from twitter.models import Person, Relationship
>>>john = Person.objects.create(name='John')
>>>paul = Person.objects.create(name='Paul')
>>>from twitter.models import RELATIONSHIP_FOLLOWING
>>>john.add_relationship(paul, RELATIONSHIP_FOLLOWING)

在这样做时,我期待这样的事情:

>>><Relationship: Relationship object>
>>>john.get_following()
>>>[<Person: Paul>]

但是,我得到错误:

AttributeError: 'Person' object has no attribute 'add_relationship'

如何查询这些对象?请指导我。

1 个答案:

答案 0 :(得分:1)

您将add_relationship()方法放在Relationship上。把它(和其他人)改为Person