我有在帖子上看到的这个模型。
模型.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'
如何查询这些对象?请引导我完成。