0

I have a Post model and Comment model. The second one based on MPTT model to achive comments arrangement in a tree format. Everything works but the problem is to restrict new child Comment to be linked with other then parent Post on creation.

Example:

Let's say I have Post objects with ID = 1 and 2. I have a parent Comment object with ID = 10 linked with Post ID = 1 (defined above). Now I can create a new child Comment object, wire it with a parent Comment but Post ID may be passed equal to 2 which is not the same as parent's one. And as a result: related comments devided in a separate Post objects. I can just make some validation like (schema without python syntax):

if new_comment.post_id != new_comment.parent__post_id:
    return Response({"error": "Child comment must be linked with the same post as parent"})

But is there any Django way to do this to make this validation work in django-admin as well? For example when I create a Comment object and choose a parent in a dropdown section then only Post related to parent Comment will be available in a dropdown section?

My code :

Models:
class Comment(MPTTModel):
    profile = models.ForeignKey(Profile, related_name="comments", on_delete=CASCADE)
    post = models.ForeignKey(Post, related_name="comments", on_delete=CASCADE)
    parent = TreeForeignKey("self", related_name="children", null=True, blank=True, 
                            on_delete=models.CASCADE)
    text = models.TextField(max_length=512)

class Post(models.Model):
    profile = models.ForeignKey(Profile, related_name="posts", on_delete=CASCADE)
    project = models.ForeignKey(Project, related_name="posts", on_delete=CASCADE)
    title = models.CharField(verbose_name="Title", max_length=150)
    body = models.TextField(verbose_name="Content", max_length=1300)

Srializers:

class CommentDTOSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False, read_only=True)
    profile = ProfileBaseDTOSerializer(read_only=True)
    post = PostBaseDTOSerializer(read_only=True)
    parent = ParentCommentDTOSerializer(read_only=True)
    text = serializers.CharField(read_only=True)

class PostDetailDTOSerializer(serializers.Serializer):
id = serializers.IntegerField(required=False, read_only=True)
    profile = ProfileBaseDTOSerializer(read_only=True)
    project = ProjectBaseDTOSerializer(read_only=True)
    title = serializers.CharField(max_length=150, read_only=True)
    body = serializers.CharField(max_length=1300, read_only=True)
Antony_K
  • 75
  • 7

0 Answers0