[Answer]-Annotate using an extra field from a ManyToMany model in Django

0πŸ‘

βœ…

At last solved it with a slight workaround:

class Product(models.Model):
    name = models.CharField(max_length=255)
    shops = models.ManyToManyField(Shop, through='ProductShop', related_name='products')
    def lowest_possible_price(self):
        shops = self.shops.all()
        if not shops:
            return "N/A"
        return reduce(lambda x, y: min(x, ProductShop.objects.get(shop__pk=y.id, product__pk=self.id).price), 
                shops, ProductShop.objects.get(shop__pk=shops[0].id, product__pk=self.id).price)

products = sorted(Product.objects.all(),
        key = lambda product : product.lowest_possible_price())

Still bothers me if there’a one-line solution with no helper function (lowest_possible_price here)

πŸ‘€Wojtek

1πŸ‘

You mean:

products = ProductShop.objects.filter(
   shop__in=Shop.objects.filter()).annotate(Min(price)).order_by('price')

{% for ps in productshop %}
    Shop: {{ ps.product.shop }}
    Product: {{ ps.product }}
    Minimum Price: {{ ps.price }}
{% endfor %}
πŸ‘€catherine

Leave a comment