簡體   English   中英

django表單-當用戶發布新評論時如何更新以前評論中的用戶數據

[英]django forms - how to update user data from previous comment when user posts a new comment

我覺得我真的很近,但還沒到那兒。 請多多包涵,因為我在學習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)
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)

模板

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

用戶評論一次= FirstName LastName1。用戶評論兩次,他的第二條評論= FirstName LastName 2,但第一條評論保持不變。

有關如何正確執行此操作的任何想法? 任何幫助是極大的贊賞!

首先,我認為您不需要review_count作為數據庫字段。 除非您打算使用它進行排序(或執行一些要求它在數據庫中的操作)。

從您的問題“ django表單-用戶發布新評論時如何從以前的評論更新用戶數據”開始,我相信您對為什么它不起作用有一個想法。

這是因為它是先前的注釋,而更新最新注釋的數據不會自動更新先前的注釋(如果默認情況下會發生災難性的:-))

無論如何,一旦刪除了review_count並將user_rating_count設置為UserProfile模型的屬性,問題就會消失。

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? 

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

{% 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 %}

如果您不願意每次加載頁面時都要重新計算該值(應該)。 Django提供了一個漂亮的裝飾器來將屬性緩存在內存中並減少數據庫負載(當您反復調用該方法/重復訪問該屬性時)

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? 

如果不需要是“數據庫”字段,則不需要。 您可以輕松地使其成為計算屬性並緩存它(如果您覺得每次重新計算都很昂貴,並且您實際上並不在乎數據的“新鮮度”)。

順便說一句,如果您需要更新舊評論(最初要使用的方式),則需要像這樣進行批量更新

我在這里太冗長了:

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

這將更新所有與過濾器參數匹配的注釋。 但是就像我說的那樣,我認為這不是您想要做的最好的方法。

讀完

https://docs.djangoproject.com/zh-CN/1.11/ref/utils/#django.utils.functional.cached_property

https://docs.djangoproject.com/zh-CN/1.11/ref/models/querysets/#update

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM