1

我有 3 个模型:

class UserProfile(models.Model):    
    slug = models.SlugField(max_length=200)
    user = models.ForeignKey(User, unique =True)
    relationships = models.ManyToManyField('self', through='Relationship',symmetrical=False,null=True, blank=True,related_name='related_to')

    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)

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

class ActivityUser(models.Model):
   slug = models.SlugField(max_length=200)
   user = models.ForeignKey('UserProfile')
   userB = models.ForeignKey('UserProfile', related_name='userFriend',null=True, blank=True)
   status = models.IntegerField(choices=NOTIFICATION_STATUS)
   date = models.DateTimeField(default=datetime.now)

基本上用户可以互相关注并且用户有活动。我希望能够从我的所有追随者和追随者那里获得所有活动。任何想法 ?谢谢

4

2 回答 2

0

您如何看待向 UserProfile 类添加另一个方法?

class UserProfile(models.Model):
    slug = models.SlugField(max_length=200)
    user = models.ForeignKey(User, unique =True)
    relationships = models.ManyToManyField('self', through='Relationship',symmetrical=False,null=True, blank=True,related_name='related_to')

    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)

    def get_all_activities(self):
        list_activities = []
        for follower in self.get_followers():
            list_activities.append(follower.ActivitieUser_set.all()        
        return list_activities
于 2013-04-09T19:02:29.717 回答
0

实际上我使用了一个查询

ActivityUser.objects.filter(
    Q(user__in=profile.get_followers()) | 
    Q(user__in=profile.get_following())).order_by("-date")
于 2013-04-09T19:07:29.297 回答