Django, annotate field with id of many-to-many field's element with lowest parameter

Viewed 796

I have the following models:

from django.db import models

class Topping(models.Model):
    # ...
    price = models.IntegerField()

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

I need to get following query:

my_query = Pizza.objects.all().annotate(
                            topping_with_min_price="get id of topping with the minimal price")

So, how to get that?

1 Answers

You can work with a Subquery:

from django.db.models import OuterRef, Subquery

my_query = Pizza.objects.annotate(
    topping_with_min_price=Subquery(
        Topping.objects.filter(
            pizza=OuterRef('pk')
        ).order_by('price').values('pk')[:1]
    )
)
Related