Set priority on Queryset in django

this is my product and category model:

class Category(models.Model):
      name = models.CharField(max_length=100)

class Product(models.Model):
      ...
      category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE)

I want a list of all products with priority order.

e.g.

categories_ids = [3,5,1,4,2]

now I want data to order like this

[product_with_category_3, product_with_category_3, product_with_category_3, product_with_category_5, product_with_category_1, product_with_category_1, ...]

We can determine the priority based on the category, and a Case-When expression:

from django.db.models import Case, Value, When

category_ids = [3, 5, 1, 4, 2]

Product.objects.filter(
    category_id__in=category_ids
).alias(
    priority=Case(*[When(category_id=k, then=Value(i)) for i, k in enumerate(category_ids)])
).order_by('priority')

This will however result in linear search so if the number of categories is large, it is not a good idea.

Вернуться на верх