R
R
Rodion Yurchenko2016-05-10 14:37:29
Django
Rodion Yurchenko, 2016-05-10 14:37:29

How to sort by choice?

Good afternoon
Model:

TICKET_STATUSES = (
        (OPEN, "OP"),
        (CLOSE, "CL"),
        (DEPRECATED, "DP"),
        (TRASH, "TR"),
    )
    title = models.CharField(max_length=100)
    status = models.CharField(max_length=2, choices=TICKET_STATUSES, default=OPEN)

View:
order_sql = '(case when status="OP" then 1 when status="CL" then 2 when status="DR" then 3 end)'
    tickets_set = Tickets.objects.filter(project_id=project_id).extra(select={'status_order': order_sql}, order_by=['status'])

It is necessary that the following order
be 1 - OP
2 - CL
3 - DP
4 - TR
But in reality it turns out that
1 - OP
2 - DP
3 - CL
4 - TR
Tell me - how should I do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2016-05-10
@sim3x

As far as I understand, the case in the database is already processed when the entire request is generated for return and it simply replaces the result in order to show it to you

TICKET_STATUS_OPEN = 1
   TICKET_STATUS_CLOSE = 2
   TICKET_STATUS_DEPRECATED = 3
   TICKET_STATUS_TRASH = 4

   TICKET_STATUSES = (
        (TICKET_STATUS_OPEN, 'OPEN'),
        (TICKET_STATUS_CLOSE, 'CLOSE'),
        (TICKET_STATUS_DEPRECATED, 'DEPRECATED'),
        (TICKET_STATUS_TRASH, 'TRASH'),
    )
    title = models.CharField(max_length=100)
    status = models.PositiveIntegerField(max_length=2, choices=TICKET_STATUSES, default=TICKET_STATUS_OPEN)

Sort simply by the field - there are just numbers there
You can do a hack like
1_OP
2_CL
3_DP
4_TR
You can stackoverflow.com/questions/883575/custom-ordering...
But on volumes it will be slow, very slow

V
Vladimir, 2016-05-10
@vintello

In short, the algorithm is the same as @sim3x wrote,
but you can also do it this way
. Add another model to store statuses and the necessary sort order. You can build a GUI so that the user can change it himself as he needs or the admin.
add a numeric field to the model with the status field indicating the sort order
on the model, catch the pre_save signal and add the sort order from the table.
sort by new field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question