How can I create a get function that returns data using only the id in Django?
Here we have the views.py file for the favorites model. The favorite model consists of two foreignkeys. One which links the favorites to the user's account, and the other that links it to the property the user favorited. I am trying to write a new get function that returns all of the properties that are favorited by a user using the parameter of the user's account id. The function should return all of the properties that are favorited with that account id.
from .models import Favorites from .serializers import FavoritesSerializer from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response class FavoritesViewSet(viewsets.ModelViewSet): queryset = Favorites.objects.all() serializer_class = FavoritesSerializer class FavoritesGetView(APIView): def get(self, request, id): snippet = Favorites.objects.get(id=id) serializer = FavoritesSerializer(snippet, many=False) return Response(serializer.data) class FavoritesPropertyGet(APIView): def get():
So far, I have tried rewriting the get function under FavoritesGetView but realized that that get function is still required. So now I am trying to write a new get function under FavoritesPropertyGet.
As per your requirement -
all of the properties that are favorited by a user using the parameter of the user's account id, I am assuming that the
id property of the
listing_account field in the
Favorites model is the user's account id.
It is not clear how you're passing the user's account id to the view, so I am assuming the user is logged in. In Django, by default the current user is present in
With the above assumptions, this should do the trick for you:
class FavoritesPropertyGet(APIView): def get(self, request): return Favorites.objects.filter(listing_account=request.user)