Reputation: 37846
I have a model:
class MyModel(models.Model):
name = models.TextField()
age = models.IntegerField(max_length=3)
I have names like: abraham lincoln
, john kennedy
, someone else
, doniyor
and many other
I want to sort them by name with this logic:
john kennedy
first.the other people should be shown after them.
I am a bit stuck because order_by()
takes fieldname and not values as parameter. How do I do this in django?
Upvotes: 1
Views: 68
Reputation: 250891
You can do this by joining two querysets, first that contains all the names with john kennedy
and second one that contains all the other names.
from django.db.models import Q
queryset1 = MyModel.objects.filter(name='john kennedy')
queryset2 = MyModel.objects.filter(~Q(name='john kennedy'))
queryset = queryset1 | queryset2
Upvotes: 3
Reputation: 122336
Use two QuerySet
objects:
from itertools import chain
q1 = MyModel.objects.filter(name='john kennedy')
q2 = MyModel.objects.exclude(name='john kennedy')
results = list(chain(q1, q2))
You're not really ordering MyModel
objects by any criteria; you're only taking some of them and putting them first. Hence this can be expressed using two queries.
Upvotes: 2