[Python] Django - how to order queryset for varying query?

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have this issue where I want to order my queryset according to a compute value based on a query in descending order.

    Query: ?fruit=Apple&?fruit=Pear

    In this case:

    Num. Apples + Num. Pears + (Num. Apples * Num. Pears)


    models.py

    class Customer(BaseModel):
    name = models.CharField('name'), max_length=255, blank=True
    fruits = models.JsonField('fruit'), null=True, blank=True, default=dict)


    My Customer.fruits looks something like this:

    fruits = { name: Apple, count: 10 },
    { name: Pear, count: 4 },
    { name: Cherry, count: 1 },
    { name: Avocado, count: 2 }


    views.py:

    def get_queryset(self):
    fruits = dict(self.request.GET).get('fruit', [])
    queryset = Customers.objects.all()
    if fruits:
    queryset = sorted(queryset, reverse = True, key=lambda customer: self.calculate_order(customer, fruits))
    return queryset

    def calculate_order(self, customer, fruits):
    value_list = [fruit['count'] for fruit in customer.fruits if fruit['name'] in fruits]
    return sum(value_list) + (reduce((lambda x, y: x*y), value_list)) if value_list else 0


    This seems to be ordering the data correctly from what I have tested so far, however doesn't seem like the best way to do it.

    Is there a better way using Django Queryset API for ordering this data? Since the way it's ordering now is a bit time consuming since I have to iterate on all the records on the database.

    Edit: I have no problem with having another model for fruits.

    class Customer(BaseModel):
    name = models.CharField('name'), max_length=255, blank=True
    fruits = models.ManytoManyField(Fruits, through='CustomerFruits')

    class Fruits(BaseModel):
    name = models.CharField('name'), max_length=255, blank=True
    count = models.IntegerField('count'), null=True, blank=True


    How can I order the customer information using this two models with the computed value?

    Continue reading...

Compartilhe esta Página