2

我有两个间接相关的表 -PostsFollower_to_followee

模型.py:

class Post(models.Model):

    auth_user = models.ForeignKey(User, null=True, blank=True, verbose_name='Author', help_text="Author")

    title = models.CharField(blank=True, max_length=255, help_text="Post Title")

    post_content = models.TextField (help_text="Post Content")

class Follower_to_followee(models.Model):

    follower = models.ForeignKey(User, related_name='user_followers', null=True, blank=True, help_text="Follower")

    followee = models.ForeignKey(User, related_name='user_followees', null=True, blank=True, help_text="Followee")

folowee 与帖子中的帖子 auth_user(帖子作者)间接相关。但是,它与 Django 用户表直接相关,而用户表与 post 表直接相关。

如何在不涉及用户表的情况下为特定关注者选择所有关注者并在查询结果中包含每个关注者的帖子计数?实际上,此时我什至不清楚如何涉及用户表。请帮忙。

4

4 回答 4

1

可以编写查询生成单个 SQL,尝试类似

qs = User.objects.filter(user_followees__follower=specific_follower).annotate(
         post_count=models.Count('post'))
for u in qs:
    print u, u.post_count

检查https://stackoverflow.com/a/13293460/165603的第二部分(除了额外的 M2M 管理器外,其他操作类似)

当在内部使用时User.objects.filter,两者user_followees__follower=foouser_followers__followee=foo都会导致Follower_to_followee模型表的连接和where条件检查follower=fooor followee=foo
(请注意user_followees__followee=foooruser_followerers__follower=foo与上面的工作方式不同,Django ORM 巧妙地简化了它们并会生成类似的东西User.objects.filter(pk=foo.pk))。

于 2013-02-13T14:28:54.570 回答
0

要获取帖子计数,您可以使用以下命令:

#get follower
follower = User.objects.get(username='username_of_fallower')
#get all followees for a specific follower
for element in Follower_to_followee.objects.filter(follower=follower):
    element.followee.post_set.all().count()
于 2013-02-13T08:47:46.077 回答
0

视图.py

def view_name(request):
    followers = Follower_to_followee.objects.filter(user=request.user)
    .......

html

{{user}}<br/>

My followers:<br/>    
{% follower in followers %}
    <p>{{follower}} - {{follower.user.follower_to_followee_set.count}}</p>
{% endfor %}
于 2013-02-13T10:27:00.763 回答
0

我不完全确定我理解这个问题,但这是一个简单的解决方案。请注意,这可以写得更简洁,但我将其分解,以便您可以看到每个步骤。

如何为特定关注者选择所有关注者?

# First grab all the follower_to_followee entries for a given 
# follower called: the_follower
follows = Follower_to_followee.objects.filter(follower=the_follower)

followee_counts = []

# Next, let's iterate through those objects and pick out 
# the followees and their posts
for follow in follows:
    followee = follow.followee

    # post for each followee
    followee_posts = Post.objects.filter(auth_user=followee).count()

    # Count number of posts in the queryset
    count = followee_posts.count()

    # Add followee/post_counts to our list of followee_counts
    followee_counts.append((followee, count))

# followee_counts is now a list of followee/post_count tuples
于 2013-02-13T08:18:39.940 回答