Here I have two models called PostComment
and AnswerComment
separately to handle comments in my web application. Now I need to have voting option for both Post and Answer comments. Therefore I though using Django GenericRelations here would be a good idea to continue. I have implemented all the parts and I can't use Django Rest Framework to post data with Django HyperlinkedRelatedField
. I'm using rest-framework-generic-relations
(link) app as DRF documentation has recommended it. It gives me following error when I try to post data.
Followings are my implementations,
Post and Answer Models,
class PostComment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class AnswerComment(models.Model):
answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Comment Model,
class VoteType(models.TextChoices):
EMPTY = 'EMPTY'
LIKE = 'LIKE'
DISLIKE = 'DISLIKE'
class CommentVote(models.Model):
voteType = models.CharField(max_length=10, choices=VoteType.choices, default=VoteType.EMPTY)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
voted_object = GenericForeignKey('content_type', 'object_id')
Serializer for vote (as implemented in the documentation),
class CommentVoteSerializer(serializers.ModelSerializer):
voted_object = GenericRelatedField({
AnswerComment: serializers.HyperlinkedRelatedField(
queryset=AnswerComment.objects.all(),
view_name='answercomment-detail'
),
PostComment: serializers.HyperlinkedRelatedField(
queryset=PostComment.objects.all(),
view_name='postcomment-detail'
),
})
class Meta:
model = CommentVote
fields = ['voted_object', 'voteType', 'owner']
View for vote,
class CommentVoteViewSet(viewsets.ModelViewSet):
queryset = CommentVote.objects.all()
serializer_class = CommentVoteSerializer
Urls for vote,
router.register(r'comment_vote', CommentVoteViewSet, basename='comment_vote_api')
Any help would be great. Thank you!