[Answer]-Django 1.6 how to first filter according to another model, then order the model?

1๐Ÿ‘

โœ…

You can make a list of filtering criteria with ordering information as a list

order_crit = {
    'python': ['votes'],
    'django': ['create_time', 'votes']
}

You can use `*` to unpack values in a list like

Question.objects.filter(label__name__contains=filter_crit).oder_by(*order_crit[filter_crit])

So if you wish to filter them by python

filter_crit = 'python'
Question.objects.filter(label__name__contains=filter_crit).order_by(*order_crit[filter_crit])

Following will result in following:

Question.objects.filter(label__name__contains='python').order_by('votes')

Because * will unpack your list as argument values within order_by. You can use multiple fields for ordering by adding the fields to the lists in order_crit

๐Ÿ‘คMp0int

0๐Ÿ‘

One option would be to make a meta class inside the mode (doc here) :

e.g.:

class Question(models.Model):
    user = models.CharField()  
    title = models.CharField()  
    content = models.TextField()
    votes = models.SmallIntegerField(default=0)

    class Meta:
        ordering = ['votes']

Also for making queries, you do not need to make array and append yourself. Django provides a lot of ways to make queries. Read here.

๐Ÿ‘คuser2707389

Leave a comment