5👍
✅
There isn’t going to be an elegant way to do this in the queryset. To do the sorting in SQL, you would have to join the MyModel
table to every other table that content_type
refers to.
You can sort in python, but note this requires one lookup per object.
queryset = list(MyModel.objects.all())
sorted_queryset = sorted(queryset, key=lambda x: x.content_object.counter)
If sorting on the counter field efficiently is really important to you, you may want to consider moving the counter field (or duplicating it) to MyModel
.
2👍
In your Model you can define an inner Meta class and define your ordering.
class MyModel(models.Model):
...
class Meta:
ordering = ['counter']
Would have to test it, but I think that is a step in the right direction.
👤esse
- [Django]-Django. success_url in view or get_absolute_url() in model. How to use them right?
- [Django]-Django Postgresql syncdb error
1👍
you can use order_by
attribute after select your object.
Mymodels.objects.all().order_by('name_field')
references : https://books.agiliq.com/projects/django-orm-cookbook/en/latest/asc_or_desc.html
- [Django]-Deleting files associated with model – django
- [Django]-How to fix "cannot unpack non-iterable NoneType object" error in django admin whilst using custom user model
- [Django]-Django app not found despite adding to INSTALLED_APPS?
Source:stackexchange.com