1👍
Your CommentSerializer
is correct problem is you are getting all comments and related replies from Comment
model in your view and passing to CommentSerializer
you need to filter and remove reply related to comment
Comment.objects.filter(reply_id__isnull=True)
0👍
set reply_id
field as write_only
class CommentSerializer(serializers.ModelSerializer):
content = serializers.CharField()
reply_id = serializers.PrimaryKeyRelatedField(
source='reply',
queryset=Comment.objects.all(),
required=False,
write_only=True
)
user = serializers.ReadOnlyField(source="user.username")
replies = CommentCreateSerializer(many=True, read_only=True)
class Meta:
model = Comment
fields = ['id', 'user', 'content', 'replies', 'reply_id', 'timestamp']
- [Answered ]-Using two models on the same Admin page
- [Answered ]-Geodjango with Mysql coordinates/polygons precision
- [Answered ]-Migration file errors when trying to get rid of a third party Django app
- [Answered ]-User Provided CSV in Django Web Project
- [Answered ]-Django REST Framework: Purpose of CreateOnlyDefault
0👍
Serializers validation will work fine in this case.
If you need to add a condition to a specific field then create a method validate_fieldname
and if you want to add condition over a specific object then directly create a method as validate
.
You can read the documentation for more information – https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation
- [Answered ]-Getting a field value from a field via a ForeignKey widget in reverse with django-import-export
- [Answered ]-Change Django alphabetical ordering to custom ordering
0👍
In your case you need to filter as @Chandan said before. So really you need to refactor your view with the reply_id
filter
permission_classes = (IsAuthenticated,)
# pagination_class = PageNumberPagination
def get(self, *args, **kwargs):
post = get_object_or_404(Post, slug=self.kwargs['slug'])
comments = Comment.objects.filter(post=post,reply_id__isnull=True)
paginator = CustomPaginator()
response = paginator.generate_response(comments, CommentSerializer, self.request)
return response
- [Answered ]-Django model has foreignkey to self. I want to get count of children?
- [Answered ]-Not able to make a GET request to the django REST API backend for the id=1 article, from axios in reactjs
- [Answered ]-Django/python: loop through a dictionary and add an item to it