[Fixed]-Annotation over Many to Many field

1👍

This can be done with .extra

legs = Leg.objects.all().order_by('date').extra(
    select={'cyclist_exists': "EXISTS(SELECT 1 FROM `myapp_cyclist_legs` \
        WHERE `myapp_cyclist_legs`.`leg_id` = `myapp_leg`.id \
          AND `myapp_cyclist_legs`.`cyclist_id` = %s)" % cyclist.id}
)

#now you can do:
for l in legs:
    print l.cyclist_exists

EDIT:

Another solution would be to take the whole Cyclist object instead of just marking boolean True/False.

Leg.objects.all().order_by('date').prefetch_related(
    Prefetch('cyclist', 
        queryset=Cyclist.objects.filter(id=cyclist.id), 
        to_attr='related_cyclist')
)

#this way every leg will have a attr `related_cyclist` 
#which will be whether an empty list or a list with one element - your cyclist object.

for l in legs:
    print l.related_cyclist
👤Todor

Leave a comment