Am having this kind of a Model, and I wanted to order by blog_views
property, how best can this be done.
This is the model :
class Post(TimeStampedModel, models.Model):
"""Post model."""
title = models.CharField(_('Title'), max_length=100, blank=False,
null=False)
# TODO: Add image upload.
image = models.ImageField(_('Image'), upload_to='blog_images', null=True,
max_length=900)
body = models.TextField(_('Body'), blank=False)
description = models.CharField(_('Description'), max_length=400,
blank=True, null=True)
slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100)
owner = models.ForeignKey(User, related_name='posts',
on_delete=models.CASCADE)
bookmarks = models.ManyToManyField(User, related_name='bookmarks',
default=None, blank=True)
address_views = models.ManyToManyField(CustomIPAddress,
related_name='address_views',
default=None, blank=True)
likes = models.ManyToManyField(User, related_name='likes', default=None,
blank=True,
)
class Meta:
ordering = ['-created']
def __str__(self):
"""
Returns a string representation of the blog post.
"""
return f'{self.title} {self.owner}'
@property
def blog_views(self):
"""Get blog post views."""
return self.address_views.all().count()
I read about annotate
but couldn't get a clear picture, how can I formulate this in my view.
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
queryset = Post.objects.all()
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = (PostsProtectOrReadOnly, IsMentorOnly)
filter_backends = [filters.SearchFilter, filters.OrderingFilter]
search_fields = ['title', 'body',
'tags__name', 'owner__email',
'owner__username'
]
I want to filter by a property in the URL
CodePudding user response:
You can't order by a method field because the ordering is done at the database level, and the database has no idea that, that field exists.
But you can use annotate
like so:
from django.db.models import Count
class PostList(generics.ListCreateAPIView):
...
queryset = Post.objects.annotate(address_views_count=Count('address_views')).order_by('address_views_count')
If you want the ordering to be optional you can use filter_queryset
:
class PostList(generics.ListCreateAPIView):
def filter_queryset(self, request, queryset, view):
ordering = self.request.GET.get("ordering", None)
if ordering == 'blog_views':
queryset = queryset.annotate(address_views_count=Count('address_views')).order_by('address_views_count')
return queryset