0

我有 2 个模型,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')

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)

我正在尝试获取 userProfile 列表,不包括 userProfile 列表,然后是某个用户。这是我的查询:

topUsersRecommendation = UserProfile.objects.exclude(id=profile.id,relationships__to_people__from_person = profile).extra(
   select={
    'num_group': """
     SELECT COUNT(*) FROM axiom_alto_groupuser gu1
     JOIN axiom_alto_groupuser gu2 on gu1.group_id = gu2.group_id
     WHERE gu2.user_id=axiom_alto_userprofile.id 
     AND gu1.user_id = %d """ % profile.id,
},

).order_by('-num_group')

但是排除似乎不起作用。谢谢你的帮助^^

4

1 回答 1

0

您可以添加一个字段来UserProfile定义如下:

followers = models.ManyToManyField(
    'self',
    blank=True,
    symmetrical=False,
    through='Relationship',
    related_name='followees'
)

IIRC然后你可以做这样的事情:

certain_user = UserProfile.objects.get(slug='Bob')
all_but_certain_user_followees = UserProfile.objects.all().exclude(
    follower = certain_user
)
于 2013-04-09T07:41:04.880 回答