1

I have a django model:

class Field:

choice = models.CharField(choices=choices)

value = models.CharField(max_length=255)  

In my database I have some cases where there are 3 "fields" with the same choice, and some cases where there is 1 field of that choice

How can I order the queryset so it returns, sorted by choice, but with all ones in a set of 3 at the start?

For example

[1,1,1,3,3,3,4,4,4,2,5] where 1,2,3,4,5 are possible choices?

2 Answers 2

0

This is the best I can do using django's ORM. Basically, just like in SQL, you have to construct a custom order_by statement. In our case, we'll place it in the SELECT and then order by it:

1) Get a list of choices sorted by frequency: [1, 3, 4, 2, 5]

freq_list = (
    Field.objects.values_list('choice', flat=True)
    .annotate(c=Count('id')).order_by('-c', 'choice')
)

2) Add indexes with enumerate: [(0,1), (1,3), (2,4), (3,2), (4,5)]

enum_list = list(enumerate(freq_list))

3) Create a list of cases: ['CASE', 'WHEN choice=1 THEN 0', ..., 'END']

case_list = ['CASE']
case_list += ["WHEN choice={1} THEN {0}".format(*tup) for tup in enum_list]
case_list += ['END']

4) Combine the case list into one string: 'CASE WHEN choice=1 THEN 0 ...'

case_statement = ' '.join(case_list)

5) Finally, use the case statement to select an extra field 'o' which will be corresponding order, then just order by this field

Field.objects.extra(select={'o': case_statement}).order_by('o')

To simplify all this, you can put the above code into a Model Manager:

class FieldManager(models.Manager):
    def get_query_set(self):
        freq_list = (
            Field.objects.values_list('choice', flat=True)
            .annotate(c=Count('id')).order_by('-c', 'choice')
        )
        enum_list = list(enumerate(freq_list))
        case_list = ['CASE']
        case_list += ["WHEN choice={1} THEN {0}".format(*tup) for tup in enum_list]
        case_list += ['END']
        case_statement = ' '.join(case_list)
        ordered = Field.objects.extra(select={'o': case_statement}).order_by('o')
        return ordered

class Field(models.Model):
    ...
    freq_sorted = FieldManager()

Now you can query:

Field.freq_sorted.all()

Which will get you a Field QuerySet sorted by frequency of choices

2
  • It seems when I implement this, Field.objects is no longer there, so Field.objects.values_list('choice', flat=True) doesn't work. Possibly as this model manager is overriding the default one - is there a way to get both?
    – entangly
    Jun 20, 2014 at 9:40
  • @entangly Yeah, you just need to explicitly include the default manager by adding objects = models.Manager() to the Field class.
    – pcoronel
    Jun 20, 2014 at 12:45
0

You should make a function and detect which is repeated to select unique, then calling from mysql as a function over mysql

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.