Answer the question
In order to leave comments, you need to log in
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)
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'])
Answer the question
In order to leave comments, you need to log in
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)
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 questionAsk a Question
731 491 924 answers to any question