python - set priority on Queryset in django - Stack Overflow

this is my product and category model:class Category(models.Model):name = models.CharField(max_length=

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, ...]

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, ...]

Share Improve this question asked Mar 12 at 8:42 Ali JoghataeeAli Joghataee 651 silver badge7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744763926a4592339.html

相关推荐

  • python - set priority on Queryset in django - Stack Overflow

    this is my product and category model:class Category(models.Model):name = models.CharField(max_length=

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信