Y
Y
Yzurgzd2020-08-08 20:20:39
Django
Yzurgzd, 2020-08-08 20:20:39

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 = "Рейтинги"


I want to return the rating set by the current user in Views
apps = App.objects.filter(draft=False).annotate(
            rating_user=models.Sum("ratings__star",
                                   filter=models.Q(ratings__user="ID текущего Пользователя"))
        )


Full Views
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

1 answer(s)
D
Dr. Bacon, 2020-08-08
@bacon

self.request.user

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question