django表单-当用户发布新评论时如何从以前的评论更新用户数据 [英] django forms - how to update user data from previous comment when user posts a new comment

查看:96
本文介绍了django表单-当用户发布新评论时如何从以前的评论更新用户数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我真的很近,但还没到那儿。



我有一个功能,用户可以在每篇博客文章中发表评论。我想在他的名字旁边显示每个用户的评论总数。如果该用户在4个不同的帖子上留下了4条评论,那么我希望它在我的整个网站上的每个评论中,在其姓名旁边显示 4条评论。



<我已经在视图中制作了一个模型方法,该方法会自动更新每个用户的评论总数。唯一的问题是,如果用户留下了两个评论,则只有他的最新评论将显示 2条评论。他的上一个只显示 1。



我的问题是,当用户留下新评论时,如何更新上一个条目?



models.py

  class Comment(models.Model):
。 ..
post = models.ForeignKey(Post,related_name = comments)
user = models.ForeignKey(User,related_name = usernamee)
email = models.EmailField(null = True,blank = True)
图片= models.TextField(max_length = 1000)
...
review_count = models.IntegerField(default = 0)

类UserProfile(models.Model):
...
def user_rating_count(self):#这是在用户的总帖子数中加上 1的原因
user_ratings =
注释。 objects.all()。filter(user_id = self.user.id).count()
user_ratings + = 1
返回user_ratings

views.py

  @login_required 
def add_comment(request ,slug):
post = get_object_or_404(Post,slug = slug)

如果request.method =='POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post =发布
comment.user = request.user
comment.email = request.user.email
comment.picture = request.user.profile.profile_image_url()
comment.review_count = request.user.profile.user_rating_count()#这是我想要更新的地方,但是它似乎无法以这种方式工作
comment.save()

return redirect('blog:post_detail',slug = post.slug)
其他:
form = CommentForm()
template = blog / post / add_comment.html
context = {

'form':form,


}
return render(request,template,context)

模板

  {在post.comments.all中的评论所占的百分比%} 
< p> {{com ment.user.first_name}}< b> {{comment.user.last_name}}< / b> {{comment.review_count}}< / p>
{%endfor%}

用户评论一次=名字姓氏1。
用户评论了两次,他的第二条评论= FirstName LastName 2,但是第一条评论保持不变。



关于如何正确执行此操作的任何想法?

解决方案

首先,我认为您不需要 review_count 为数据库字段。



从您的问题 django表单-如何从中更新用户数据中,您打算使用它进行排序(或执行某些要求将其存储在数据库中的操作)。 先前的评论(当用户发布新评论时)。我相信您对为什么它不起作用有一个想法。



这是因为它是先前的评论,更新最新评论的数据不会自动更新以前的评论(如果默认情况下会发生灾难性的灾难:-))



无论如何,删除 review_count 并使 user_rating_count 成为 UserProfile 模型的属性

  class UserProfile(models.Model):

@property
def user_rating_count (个体):
这是在用户的总帖子数中添加 1的原因

return self.usernamee.count()#记住您的 related_name早点设置?

然后您可以在模板中使用它

  {%为post.comments.all%中的评论} 
< p> {{comment.user.first_name}}< b> {{评论。 user.last_name}}< / b> {{request.user.profile.user_rating_count}}< / p>
{%endfor%}

如果您不满意每个值的重新计算值页面加载(应该)。 Django提供了一个漂亮的装饰器,可以将属性缓存在内存中并减少数据库的负载(当您调用该方法/重复访问该属性时)

 从django.utils.functional导入cached_property 


类UserProfile(models.Model):

@cached_property
def user_rating_count(self ):
这是在用户的总帖子数中添加 1的原因

return self.usernamee.count()#记住您之前设置的`related_name` ?

如果不需要是数据库字段,则不需要。您可以轻松地使其成为计算属性并缓存它(如果您觉得每次重新计算都很昂贵,并且您实际上并不关心数据的新鲜度)。



如果您需要更新旧评论(最初要使用的方式),您将像这样进行批量更新



在这里过于冗长:

 评论= Comment.objects.filter(user_id = self.user.id)
count = comments.count()
comments.update(review_count = count)

这将更新与过滤器参数匹配的所有注释。但是就像我说的那样,我认为这不是您想要做的最好的方法。



阅读



https://docs.djangoproject。 com / en / 1.11 / ref / utils /#django.utils.functional.cached_property





https://docs.djangoproject.com/en/ 1.11 / ref / models / querysets /#update


I feel like I'm really close, but not quite there yet. Please bear with me as I am very much so in the beginner stages of learning django.

I have a feature where users can comment on each blog post. I want to display the total number of comments each user has next to his name. If that user has left 4 comments on 4 different posts, I want it to show "4 total comments" next to his name on each one of his individual comments throughout my website.

I have made a model method that I put in my view, which automatically updates the total comments for each user. The only problem is that if the user has left two comments, only his latest comment will show "2 total comments". His previous one shows only "1".

My question is, how do I make the previous entry update when the user has left a new comment?

models.py

class Comment(models.Model):
...
post = models.ForeignKey(Post, related_name="comments")
user = models.ForeignKey(User, related_name="usernamee")
email = models.EmailField(null=True, blank=True)
picture = models.TextField(max_length=1000)
...
review_count = models.IntegerField(default=0)

class UserProfile(models.Model):
...
def user_rating_count(self): #This is what adds "1" to the user's total post count
    user_ratings = 
    Comment.objects.all().filter(user_id=self.user.id).count()
    user_ratings += 1
    return user_ratings

views.py

@login_required
def add_comment(request, slug):
    post = get_object_or_404(Post, slug=slug)

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post 
            comment.user = request.user 
            comment.email = request.user.email
            comment.picture = request.user.profile.profile_image_url()
            comment.review_count = request.user.profile.user_rating_count() #This is where I'd like it to update, but it doesn't seem to work this way
            comment.save()

            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()
    template = "blog/post/add_comment.html"
    context = {

        'form': form,


        }
    return render(request, template, context)

template

{% for comment in post.comments.all %}
    <p>{{ comment.user.first_name }} <b>{{ comment.user.last_name }}</b> {{ comment.review_count }}</p>
{% endfor %}

User comments once = FirstName LastName 1. User comments twice, his second comment = FirstName LastName 2, but the first comment remains unchanged.

Any ideas on how to properly do this? Any help is greatly appreciated!

解决方案

First i don't think you need the review_count to be a Database field. Except you plan to use it to sort (or do something that requires it to be in the Database).

From your question "django forms - how to update user data from previous comment when user posts a new comment" I believe you have an idea on why it's not working.

It's because it's a previous comment and Updating the data of the latest comment won't automatically update the previous comments (It would be disastrous if that happened by default :-) )

Anyway once you remove thereview_count and make user_rating_count a property of the UserProfile model your problem disappears.

class UserProfile(models.Model):

    @property
    def user_rating_count(self):
        """This is what adds "1" to the user's total post count"""

        return self.usernamee.count()  # Remember the `related_name` you set earlier? 

Then you can use it in your templates like this

{% for comment in post.comments.all %}
    <p>{{ comment.user.first_name }} <b>{{ comment.user.last_name }}</b> {{ request.user.profile.user_rating_count }}</p>
{% endfor %}

If you're bothered about the value being recalculated on each page load (You should be). Django provides a nifty decorator to cache the property in memory and reduce the load on your database (When you call the method/access the property repeatedly)

from django.utils.functional import cached_property


class UserProfile(models.Model):

    @cached_property
    def user_rating_count(self):
        """This is what adds "1" to the user's total post count"""

        return self.usernamee.count()  # Remember the `related_name` you set earlier? 

If it doesn't need to be a Database field, it doesn't need to be. You can easily make it a computed property and Cache it (If you feel it's expensive to recalculate everytime and you don't really care about the "freshness" of the data).

By the way if you needed to update the Old comments (The way you wanted to initially), You would've done a batch update like this

I'm being overly verbose here:

comments = Comment.objects.filter(user_id=self.user.id)
count = comments.count()
comments.update(review_count=count)

That will update all the comments that match the filter params. But like i said i don't think this is the best approach for what you want to do.

Read up

https://docs.djangoproject.com/en/1.11/ref/utils/#django.utils.functional.cached_property

and

https://docs.djangoproject.com/en/1.11/ref/models/querysets/#update

这篇关于django表单-当用户发布新评论时如何从以前的评论更新用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆