Skip to content Skip to sidebar Skip to footer

Bookmarking Function Django/python

I'm looking to create a model for users to bookmark a recipe. I have the below: models.py class RecipeBookmark(models.Model): recipe = models.ForeignKey( Recipe, on_de

Solution 1:

If you want your serializer to ensure that only one bookmark is created per user per recipe, you can use get_or_create:

    def create(self, validated_data):
        request = self.context["request"]
        ModelClass = self.Meta.model

        instance = ModelClass.objects.get_or_create(
            **validated_data, **{"bookmarked_by": request.user}
        )
        return instance

If the bookmark is already present, it will just grab it and return.

Also, How can a lookup be performed to return recipes that a logged in user has bookmarked via an api endpoint?

To support this, you can define ListCreateAPIView to your view and override the queryset like so:

class RecipeBookmarkView(generics.ListCreateAPIView):
    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(bookmarked_by=self.request.user)

This will then support getting all the RecipeBookmark that is owned by the current user via GET requests on recipes/bookmarks/


Post a Comment for "Bookmarking Function Django/python"