I’ve been trying to create rest-api social network, when I create new action inside views, is it a must to send pk (primary key) as parameter?
because I created method with GET action, and it didn’t work until I sent a pk in the url,
views.py
class ProfileView(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializers
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
@action(detail=True, methods=["GET"])
def get_friends_request(self, request,pk):
try:
reciver = request.user
friend_requests = FriendRequest.objects.filter(reciver=reciver)
serializer = FriendRequestSerializers(friend_requests, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
except:
response = {"message": "something went wrong"}
return Response(response, status=status.HTTP_400_BAD_REQUEST)
models.py
class Profile(models.Model):
"""a model which contain all the fields that is needed for user's profile or account, and it's not needed for authentication"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=False,
blank=False,
)
username = models.CharField(max_length=200, null=False, blank=False, default=None)
bio = models.TextField(
blank=True, null=True, max_length=400, default="no bio yet..."
)
joined_date = models.DateField(null=True, blank=True, default=date.today)
picture = models.ImageField(upload_to="images/", blank=True, null=True)
private = models.BooleanField(default=False)
class FriendRequest(models.Model):
sender = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=False,
blank=False,
on_delete=models.CASCADE,
related_name="sender_set",
)
reciver = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=False,
blank=False,
on_delete=models.CASCADE,
related_name="reciver_set",
)
status = models.CharField(
null=False, choices=STATUS_CHOICES, default=STATUS_CHOICES[0][0]
)
created_at = models.DateField(null=False, blank=False, default=date.today)
another question, I have other models that has profile field as a fk to Profile Model ex: comment Model, Like Model , post Model ,etc
is it recommend it to write methods like get_post,get_likes;get_comments in ProfileView to get all the objects that is related to one Profile object?
is there any need to write this methods?