2

I have two models in my Django database:

class Member(models.Model):
    signed_up_to=models.ManyToManyField(Piece)
class Piece(models.Model):
    title = models.CharField(max_length=200,null=True,blank=True)

When I pull Piece objects from my database, I would like to annotate (Bool or Integer) whether or not the Piece appears in signed_up_to of a specific Member. I've looked around for an answer all over the internet, but with no success. Hope there's anyone who can help me!

1 Answer 1

2

Given the Member object is member, you can make use of an Exists subquery [Django-doc]:

from django.db.models import Exists, OuterRef

Piece.objects.annotate(
    has_member=Exists(
        Member.signed_up_to.through.objects.filter(
            piece_id=OuterRef('pk'),
            member_id=member.pk
        )
    )
)

So has_member will be True if member has this Piece object in its signed_up_to relation, and False otherwise.

Sign up to request clarification or add additional context in comments.

4 Comments

Perfect! Dankjewel Willem!
Oh, for Christ's sake. Man, I admire you so bad. This is perfect... Could you please share with me what's the need of using OuterRef? I just don't get it, because the docs say that you should use it if you're going to refer a field from the subquery, but in your example (and in the example used in the docs) I don't see that usage. @Willem
@revliscano: it means we take the pk (so the id field) of the outer query of this subquery, so the id of the Piece object.
@revliscano Exists is a subclass of Subquery.

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.