A
A
Andrey Salnikov2017-09-27 15:23:57
Django
Andrey Salnikov, 2017-09-27 15:23:57

How to add model elements to the end of the list?

There is a model:

class A(models.Models):
    price = models.DecimalField(decimal_places=2, max_digits=12, default=0, verbose_name='Цена')
    stock = models.PositiveIntegerField(blank=True, default=0)

I need to check the following.
Sort by price, but at the same time, so that the elements with stock = 0 are at the end of the list.
Did it like this:
a = A.objects.all()
b = a.filter(stock__gt=0).order_by('-price')
c = a.filter(stock=0).order_by('-price')
x = set()
x.update(b)
x.update(c)
return list(x)

Only this does not work and the elements are still mixed into a heap. How to solve this problem correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Segey K., 2017-09-27
@Shshzik

from itertools import chain
b = a.filter(stock__gt=0).order_by('-price')
c = a.filter(stock=0)
x = chain(b, c)

Can it be like this

V
Vlad Grigoriev, 2017-09-27
@Vaindante

All just read what set is here and the first links will give the right answer.

A
Astrohas, 2017-09-27
@Astrohas

a = A.objects.all()
a.annotate(
        zero_price = Case(
            When(price=0, then=Value(1)),
            default = Value(0),
            output_field = IntegerField()
        )
    ).order_by("zero_price", "price")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question