0

I have a problem with creating a modelfield which Count number of people who like an article. I have class Like:

class Reaction(models.Model):
    user = models.ForeignKey(User)
    article = models.IntegerField(null=True, blank=True)
    date = models.DateTimeField(auto_now_add=True, null=True)

and class Article:

from api.reactions.models import Reaction
class Article(models.Model):    
    user = models.ForeignKey(User)
    post = models.TextField()
    likes = models.IntegerField(default=0)

    def __str__(self):
        return self.post

    def calculate_likes(self):
        likes = Reaction.objects.count(article=self.pk)
        self.likes = likes
        self.save()
        return self.likes

But likes wont be counted. What's wrong with this? Please help me. Thanks!

4
  • what is pk here at 4th last line ? Commented Nov 23, 2017 at 18:12
  • article id, @Doda Commented Nov 23, 2017 at 18:13
  • No relationship between Article and Reaction??? Commented Nov 23, 2017 at 19:04
  • In this line: article = models.IntegerField(null=True, blank=True), I use IntegerField to return article ID. Commented Nov 24, 2017 at 7:20

1 Answer 1

1
def get_likes(self):
        return self.likes.all().count()

this should basically be it, you don't need to point a model to an instance of itself, creating a reaction class is overkill. But if you are still going for it instead of:

likes = Reaction.objects.count(article=self.pk)

Try:

likes = Reaction.objects.filter(article=self.pk).count()
Sign up to request clarification or add additional context in comments.

2 Comments

I try all your 3 solutions but it's not work. Use def is not return count. Solution 2 and 3, it came to error: name 'self' is not defined
u can try 'likes = Reaction.objects.filter(article__1contains=self.id).count()'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.