У меня есть приложение для блога, в котором пользователи могут добавлять новые сообщения, и они могут понравиться любым пользователям.
models.py
class Post(models.Model):
title = models.CharField(max_length=60)
class PostLikes(models.Model):
likeusers = models.ManyToManyField(User)
likepost = models.ForeignKey(Post,on_delete=models.CASCADE,null=True,related_name='likepost')
сериализаторы .py
class PostSerializers(serializers.ModelSerializer):
#likepost = serializers.SerializerMethodField() **I have to mention like count here**
class Meta:
model = Post
fields = '__all__'
class PostlikeSerializer(serializers.ModelSerializer):
class Meta:
model = PostLikes
fields = '__all__'
views.py
class LikeListCreate(APIView):
def get(self,request,pk):#function to get total number of likes to particular post
post = Post.objects.filter(pk=pk) # find which post's likes are to be extracted
like_count = post.likepost.count()# counts total user likes ,besides my code is wrong
serializer = PostlikeSerializer(like_count,many=True)
return Response(serializer.data)
def post(self,request,pk):#function to add likes to post
# how do I check if user is already liked the post ?
likeusers = request.user
likepost = Post.objects.filter(pk=pk)
serializer = PostlikeSerializer(data=request.data)
if serializer.is_valid():
serializer.save(likeusers,likepost)
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
urls.py
path('posts/<int:pk>/like/',LikeListCreate.as_view(),name = 'post_likes'),
Я не могу реализовать logi c в модуле views.py и разделе serializers.py. Помогите пожалуйста, заранее спасибо
Git ссылка на мой проект https://github.com/Anoop-George/BlogApp.git