英文:
How do I calculate the total number of likes for all of a user's posts in Django?
问题
我正在研究一个Django项目,尝试根据用户的帖子计算他们的总点赞数(即如果用户有一篇帖子有10个赞,另一篇有5个,总赞数应显示为15)。我尝试了各种方法,但未能使其正常工作。
以下是我的models.py部分内容:
class User(AbstractUser):
username = models.CharField(...)
first_name = models.CharField(...)
last_name = models.CharField(...)
email = models.EmailField(...)
bio = models.CharField(...)
...
class Post(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
text = models.CharField(max_length=280)
created_at = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name="user_post")
def total_likes(self):
return self.likes.count()
class Meta:
ordering = ["created_at"]
接下来,我尝试在HTML文件(用户个人资料)中显示特定用户所有帖子的总赞数:
...
<p>Total likes: {{ post.likes.all.count }}</p>
...
views.py部分内容如下:
@login_required
def show_user(request, user_id):
try:
user = User.objects.get(id=user_id)
posts = Post.objects.filter(author=user)
except ObjectDoesNotExist:
return redirect('user_list')
else:
return render(request, 'show_user.html', {'user': user , 'posts' : posts, 'request_user': request.user})
到目前为止,我尝试过以下方法:
-
最初,我尝试使用
{{ post.likes.all.count }}
模板标签来显示每篇帖子的总点赞数。然而,这没有有效果,屏幕上没有返回任何值。 -
接下来,我尝试在循环内使用
{% add %}
模板标签来遍历所有帖子并累积点赞数。但是,这导致了TemplateSyntaxError错误。
我不确定解决此问题的最佳方法是什么。非常感谢您提供关于如何在Django中计算和显示用户所有帖子的总点赞数的指导或建议。
英文:
I'm working on a Django project and I'm trying to calculate the total number of likes for a user based on their posts (i.e if a user has post with 10 likes and another with 5, the total likes must display 15) . I've tried various approaches, but I haven't been able to get it working.
Here is my models.py:
class User(AbstractUser):
username = models.CharField(...)
first_name = models.CharField(...)
last_name = models.CharField(...)
email = models.EmailField(...)
bio = models.CharField(...)
...
class Post(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
text = models.CharField(max_length=280)
created_at = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name="user_post")
def total_likes(self):
return self.likes.count()
class Meta:
ordering = ["created_at"]
And here I am trying to display the total number of likes for all posts from a specific user inside this html file (user profile):
...
<p>Total likes: {{ post.likes.all.count }} </p>
...
views.py
@login_required
def show_user(request, user_id):
try:
user = User.objects.get(id=user_id)
posts = Post.objects.filter(author=user)
except ObjectDoesNotExist:
return redirect('user_list')
else:
return render(request, 'show_user.html', {'user': user , 'posts' : posts, 'request_user': request.user})
Here's what I've tried so far:
-
Initially, I attempted to use the
{{ post.likes.all.count }}
template tag to display the total number of likes for each post. However, this didn't work as it didn't return any value on the screen. -
Next, I tried using the {% add %} template tag within a loop to iterate over all the posts and accumulate the likes count. However, this resulted in a TemplateSyntaxError.
I am not sure what the best way to solve this issue is. I would greatly appreciate any guidance or suggestions on how to calculate and display the total number of likes for a user's from all posts in Django.
答案1
得分: 3
以下是翻译的内容:
你可以通过以下方式确定作者的总点赞数:
from django.db.models import Count
@login_required
def show_user(request, user_id):
user = get_object_or_404(
User.objects.annotate(total_likes=Count('post__likes')), pk=user_id
)
posts = Post.objects.filter(author=user)
return render(
request,
'show_user.html',
{'user': user, 'posts': posts, 'request_user': request.user},
)
在模板中,你可以通过以下方式渲染用户的总点赞数:
{{ user.total_likes }}
你还可以提高计算每篇帖子的点赞数的效率:
from django.db.models import Count
@login_required
def show_user(request, user_id):
user = get_object_or_404(
User.objects.annotate(total_likes=Count('post__likes')), pk=user_id
)
posts = Post.objects.annotate(num_likes=Count('likes')).filter(author=user)
return render(
request,
'show_user.html',
{'user': user, 'posts': posts, 'request_user': request.user},
)
在模板中,你可以通过以下方式渲染这个值:
{% for post in posts %}
{{ post }} (点赞数:{{ post.num_likes }})
{% endfor %}
请注意:通常最好使用 get_object_or_404(...)
来获取对象,而不是直接使用 .get(...)
。如果对象不存在,例如因为用户自行修改了URL,get_object_or_404(...)
将返回一个 HTTP 404 Not Found 响应,而使用 .get(...)
将导致 HTTP 500 Server Error。
另请注意:通常最好使用 settings.AUTH_USER_MODEL 来引用用户模型,而不是直接使用 User 模型。有关更多信息,请参阅文档中的 引用 User 模型 部分。
英文:
You can determine the total number of likes for an author with:
<pre><code>from django.db.models import Count
@login_required
def show_user(request, user_id):
user = get_object_or_404(
User.objects.annotate(<b>total_likes=Count('post__likes')</b>), pk=user_id
)
posts = Post.objects.filter(author=user)
return render(
request,
'show_user.html',
{'user': user, 'posts': posts, 'request_user': request.user},
)</code></pre>
in the template you can then render the total likes of the user with:
<pre><code>{{ user<b>.total_likes</b> }}</code></pre>
You can also boost counting the number of likes per post with:
from django.db.models import Count
<pre><code>@login_required
def show_user(request, user_id):
user = get_object_or_404(
User.objects.annotate(total_likes=Count('post__likes')), pk=user_id
)
posts = Post.objects.annotate(<b>num_likes=Count('likes')</b>).filter(author=user)
return render(
request,
'show_user.html',
{'user': user, 'posts': posts, 'request_user': request.user},
)</code></pre>
In the template you can then render this with:
<pre><code>{% for post in posts %}
{{ post }} (likes: {{ post<b>.num_likes</b> }})
{% endfor %}</code></pre>
> Note: It is often better to use <code>get_object_or_404(…)</code> <sup>[Django-doc]</sup>,
> then to use <code>.get(…)</code> <sup>[Django-doc]</sup> directly. In case the object does not exists,
> for example because the user altered the URL themselves, the <code>get_object_or_404(…)</code> will result in returning a HTTP 404 Not Found response, whereas using
> <code>.get(…)</code> will result in a HTTP 500 Server Error.
> Note: It is normally better to make use of the settings.AUTH_USER_MODEL
<sup>[Django-doc]</sup> to refer to the user model, than to use the User
model <sup>[Django-doc]</sup> directly. For more information you can see the referencing the User
model section of the documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论