user9654219
user9654219

Reputation:

Django: Updating the Integer Field

I have an app in which a user can ask a question & answer it. My problem is that I couldn't increase the answer views as the question is called. Have a detailed look,

Here is the model,

class Question(models.Model):
    . . .

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer_views = models.IntegerField(default=1)
    . . .

In my view,

def question_detail(request, id):
    my_question = Question.objects.get(id=id)

Now in the html file, I can easily print the Question & all of it's related answers by using my_question.answer_set.all.

So, as a specific question (my_question) is called I wants to increase the number of view on all of it's related answers by 1. How can I do that?

Thank You!

Upvotes: 1

Views: 1292

Answers (1)

ascripter
ascripter

Reputation: 6223

If you don't need to listen to any signals, you can directly update all related answers using F()expressions:

from django.db.models import F

def question_detail(request, id):
    my_question = Question.objects.get(id=id)
    my_question.answer_set.update(answer_views=F('answer_views') + 1)

Upvotes: 2

Related Questions