'Django | Filter Ordering - How to implement "ordering" when you use @property
please help me to make the correct "ordering" for a "custom" property some_property_field. I write such an URL and it doesn't work. I understand the reason is a "custom" property. How to work it out?
/api/articles/?ordering=-some_property_field
urls.py
router = DefaultRouter()
router.register(r'articles', ArticleViewSet, basename='articles')
urlpatterns = []
urlpatterns += router.urls
models.py
class Article(models.Model):
title = models.CharField(max_length=20)
description = models.TextField()
def __str__(self):
return self.title
@property
def some_property_field(self):
return f'{self.title} property func'
views.py
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
ordering_fields = ('id', 'title', 'some_property_field')
ordering = ('id',) # default ordering
serializers.py
class ArticleSerializer(serializers.ModelSerializer):
some_property_field = serializers.CharField(read_only=True)
class Meta:
model = Article
fields = '__all__'
Solution 1:[1]
Ordering is done in queryset so you can only use field that exists in database.
If you want to order by property you need to do that in python:
qs = sorted(Article.objects.all(), key=lambda obj: obj.some_property_field)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bartosz Stasiak |
