Home > Mobile >  Listing objects field instead of Object in Django Rest Framework
Listing objects field instead of Object in Django Rest Framework

Time:02-18

I've got a model

class Like(models.Model):
    product = models.ForeignKey('ProductInStore', on_delete=models.PROTECT)
    user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT)

    class Meta:
        unique_together = ('product', 'user',)

and a serializer

class LikeSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    product = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Like
        fields = ('user', 'product',)

class UserLikedProductsApiList(generics.ListAPIView):
    queryset = Like.objects.all()
    serializer_class = LikeSerializer

And so if someone likes a product, adds it to favourites, it creates an Like object in database. And i want to create an endpoint users/me/likedProducts so that i can list all the products that self.user.request has liked. Meaning all the Like instances but instead of Like instances i want to show only Like.product instances. Lets say a person x has liked 4 items, and i want to show only 4 items in that list. Do you have any idea how to get around that in Django Rest Framework?

CodePudding user response:

you can change the queryset from like model to ProductInStore model the query would look like this: ProductInStore.objects.filter(id__in=Like.objects.filter(user=self.request.user).values_list('product',flat_true)) and you can use the default product serializer

  • Related