我如何计算Django中用户所有帖子的总点赞数?

huangapple go评论92阅读模式
英文:

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})

到目前为止,我尝试过以下方法:

  1. 最初,我尝试使用{{ post.likes.all.count }}模板标签来显示每篇帖子的总点赞数。然而,这没有有效果,屏幕上没有返回任何值。

  2. 接下来,我尝试在循环内使用{% 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=&quot;user_post&quot;)

    def total_likes(self):
        return self.likes.count()

    class Meta:
        ordering = [&quot;created_at&quot;]

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):

...
    &lt;p&gt;Total likes: {{ post.likes.all.count }} &lt;/p&gt;
...

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(&#39;user_list&#39;)
    else:
        return render(request, &#39;show_user.html&#39;, {&#39;user&#39;: user , &#39;posts&#39; : posts, &#39;request_user&#39;: request.user})
        

Here's what I've tried so far:

  1. 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.

  2. 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(&hellip;)</code>&nbsp;<sup>[Django-doc]</sup>,
> then to use <code>.get(&hellip;)</code>&nbsp;<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(&hellip;)</code> will result in returning a HTTP 404 Not Found response, whereas using
> <code>.get(&hellip;)</code> will result in a HTTP 500 Server Error.


> Note: It is normally better to make use of the settings.AUTH_USER_MODEL&nbsp;<sup>[Django-doc]</sup> to refer to the user model, than to use the User model&nbsp;<sup>[Django-doc]</sup> directly. For more information you can see the referencing the User model section of the documentation.

huangapple
  • 本文由 发表于 2023年6月5日 05:06:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定