Since Django 1.8, you can do:
from django.db.models import Case, When
pk_list = [10, 2, 1]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)
More Related Contents:
- Django Cookies, how can I set them?
- Django rest framework nested self-referential objects
- How to ‘bulk update’ with Django?
- Django REST Framework: adding additional field to ModelSerializer
- Use variable as dictionary key in Django template
- Django multiprocessing and database connections
- Caching query results in django
- Django delete FileField
- Raise a validation error in a model’s save method in Django
- Overriding admin css in django
- SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
- How can I get a favicon to show up in my django app?
- Django: show a ManyToManyField in a template?
- Django: ordering numerical value with order_by
- Access kwargs from a URL in a Django template
- How to register users in Django REST framework?
- How to do a multi-step form in Django?
- Example of Django Class-Based DeleteView
- Accelerate bulk insert using Django’s ORM?
- Pass request context to serializer from Viewset in Django Rest Framework
- Django: permission denied when trying to access database after restore (migration)
- UnicodeEncodeError: ‘ascii’ codec can’t encode character
- How can I upload and download files with graphene-django?
- Django give Error 500 for all static files like CSS and Images, when DEBUG is False
- Authorization Credentials Stripped — django, elastic beanstalk, oauth
- How to use if/else condition on Django Templates?
- Django query case-insensitive list match
- Django/DRF – 405 Method not allowed on DELETE operation
- django : Serving static files through nginx
- Django: Using F arguments in datetime.timedelta inside a query