我有两个间接相关的表格 - Posts
和Follower_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表直接相关。
如何为特定关注者选择所有关注者,并在查询结果中包含每个关注者的帖子计数,而不涉及用户表?实际上,在这一点上,我甚至不知道如何涉及用户表。请帮忙。
答案 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=foo
和user_followers__followee=foo
都会导致加入Follower_to_followee
模型表和where
条件检查{ {1}}或follower=foo
(请注意,followee=foo
或user_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 %}