Answer the question
In order to leave comments, you need to log in
Return current user with Django Rest Framework?
How to return current logged in user? Used by Djoser + Simple JWT
Models
class Rating(models.Model):
user = models.ForeignKey(
UserProfile, verbose_name="Имя пользователя", on_delete=models.CASCADE)
star = models.PositiveSmallIntegerField(
"Звезда", validators=[MaxValueValidator(5)], default=0)
app = models.ForeignKey(
App,
on_delete=models.CASCADE,
verbose_name="приложение",
related_name="ratings"
)
def __str__(self):
return f"{self.star} - {self.app}"
class Meta:
verbose_name = "Рейтинг"
verbose_name_plural = "Рейтинги"
apps = App.objects.filter(draft=False).annotate(
rating_user=models.Sum("ratings__star",
filter=models.Q(ratings__user="ID текущего Пользователя"))
)
class AppViewSet(viewsets.ReadOnlyModelViewSet):
filter_backends = (DjangoFilterBackend, filters.SearchFilter)
search_fields = ['title', ]
filterset_class = AppFilter
pagination_class = PaginationApps
lookup_field = 'slug'
def get_queryset(self):
apps = App.objects.filter(draft=False).annotate(
rating_user=models.Sum("ratings__star",
filter=models.Q(ratings__user="ID текущего Пользователя"))
).annotate(
middle_star=models.Sum(models.F('ratings__star')) /
models.Count(models.F('ratings'))
)
return apps
def get_serializer_class(self):
if self.action == 'list':
return AppListSerializer
elif self.action == "retrieve":
return AppDetailSerializer
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question