Django:如何添加非相关对象的计数?

时间:2013-02-12 18:37:14

标签: sql django count relation

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

models.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")

该帖子与帖子中的post auth_user(帖子后发布者)间接相关。但是,它与Django用户表直接相关,用户表与post表直接相关。

如何为特定关注者选择所有关注者,并在查询结果中包含每个关注者的帖子计数,而不涉及用户表?实际上,在这一点上,我甚至不知道如何涉及用户表。请帮忙。

4 个答案:

答案 0 :(得分: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条件检查{ {1}}或follower=foo
 (请注意,followee=foouser_followees__followee=foo的工作方式与上述不同,Django ORM可以巧妙地简化它们,并生成类似user_followerers__follower=foo的内容。

答案 1 :(得分: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

答案 2 :(得分: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()

答案 3 :(得分:0)

<强> views.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 %}