Sequencing using SQL syntax CASE WHEN / THEN django

I am trying to order contacts in a table, and I ran into some problems, I found a good solution in this question https://stackoverflow.com/a/4646262/2326 , maybe this is more than that, but I'm trying to do it on restapi . therefore, I only influence my opinion on rest, so this is my solution for this order:

 filter_date = self.request.query_params.get('filter_date', None) case_sql = '(case when status="Client" ' \ 'then 1 when status="Contacted" ' \ 'then 2 when status="Qualified" ' \ 'then 3 when status="Virgin" then 4 end)' if filter_date is not None: queryset = queryset.filter(next_action_date=filter_date).extra(select={'status': case_sql}, order_by=['status']) 

I do this because I don’t want to change my db field, for example, I said that I only want to influence my view of rest, so the question is that I am doing this filter incorrectly, does it all go wrong by default?

Model Fields:

 status = models.CharField(max_length=10, choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE) 

and the choice for this field:

 class LeadContactConstants(object): STATUS_PRISTINE = "PRISTINE" STATUS_CONTACTED = "CONTACTED" STATUS_QUALIFIED = "QUALIFIED" STATUS_CLIENT = "CLIENT" STATUSES = ((STATUS_PRISTINE, "Virgin"), (STATUS_CONTACTED, "Contacted"), (STATUS_QUALIFIED, "Qualified"), (STATUS_CLIENT, "Client")) 
0
source share
1 answer

This question you have contacted is from 2012. Since then, much has changed, for example, the inclusion of ..... CASE / WHEN in Django .

The expression Case () is similar to the expression if ... elif ... else in Python. Each condition in the provided When () objects is evaluated in until you evaluate the true value. Expression of the result from the returned object Return ().

The whole idea is that you do not need to write complex queries, as you sometimes had to.

Standard practice is to create an annotation with CASE / WHEN and then use it in the annotation in the order

+2
source

All Articles