TransWikia.com

How to annotate a value from a related model in Django

Stack Overflow Asked by Roman Safonov on December 15, 2020

I have a Post model:

class Post(models.Model, NiceTextPrintMixin):
    text = models.TextField()
    pub_date = models.DateTimeField("date published",
                                    auto_now_add=True,
                                    db_index=True)
    author = models.ForeignKey(User,
                               on_delete=models.CASCADE,
                               related_name="posts")
    group = models.ForeignKey(Group,
                              on_delete=models.SET_NULL,
                              blank=True,
                              null=True,
                              related_name="posts",
                              )
    image = models.ImageField(upload_to='posts/', blank=True, null=True)

and a Like model:

class Like(models.Model):
    post = models.ForeignKey(Post,
                             on_delete=models.CASCADE,
                             blank=False,
                             null=False,
                             related_name="likes")

    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             blank=False,
                             null=False,
                             related_name="likes")

    value = models.IntegerField()

What i need is to annotate a field to a Post queryset that would contain a ‘value’ value from a Like model where the post_id=corresponding post_id and user=request.user if such a record exists and 0 (None is also fine) if it doesn’t. Is there a way to get that done in a simple annotate way ?

2 Answers

Maybe try this

from django.db.models import Count, Case, When, IntegerField
posts_wth_like = Post.objects.all().annotate(count_like=Count(Case(When(likes__user=user, then=1),output_field=IntegerField(),)))

If user have like = 1 , else 0

Answered by Boris Golubkov on December 15, 2020

You can't pass arguments in @property. You can implement method for Post:

def get_like_value(user):
    try:
        like = Like.objects.get(user = user, post = self,)
        return like.value
    catch Like.DoesNotExist:
        return 0

Answered by Boris Golubkov on December 15, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP