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
- [Answer]-Django: is_secure() decorator not working
- [Answer]-Model name is being displayed in Django template
Source:stackexchange.com