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",
    author = models.ForeignKey(User,
    group = models.ForeignKey(Group,
    image = models.ImageField(upload_to='posts/', blank=True, null=True)

and a Like model:

class Like(models.Model):
    post = models.ForeignKey(Post,

    user = models.ForeignKey(User,

    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):
        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!

Related Questions

Update a with react

1  Asked on December 30, 2021 by mara-oliveira


Euclidean distance of all pandas rows to single row

1  Asked on December 30, 2021 by aquamad96


Different result with online compiler and visual code

0  Asked on December 30, 2021 by swayamjeet-swain


recursive function debug asserion failed

2  Asked on December 30, 2021 by steven-zhou


SQL Grant Execute On Object where do I put GO?

2  Asked on December 30, 2021 by andy-williams


Split string by comma unless followed by a space or a ‘+’

3  Asked on December 30, 2021 by callum-brown


Get values of cells in dataframe column quickly

2  Asked on December 30, 2021 by user11035198


Parsing XML values in Javascript

2  Asked on December 30, 2021 by topcat3


split sequences

1  Asked on December 30, 2021 by backgroup


when checkbox checked value true, display text not displayed

4  Asked on December 30, 2021 by user11247496


.net core 2.0 logging inside Kubernetes pod console

1  Asked on December 30, 2021 by abhay


XML vs JSON vs SQLite for only reading data

9  Asked on December 30, 2021 by brandon-cornelio


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP