Skip to content

Set custom "type" for ResourceRelatedField #193

@EmilTemirov

Description

@EmilTemirov

Hi, all!
I have the following Django model:

class Comment(model.Model):
    text = models.TextField()
    parent_comment = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)

I want to be able to obtain a list of comments with "parent" in relationships, for example:

{
  "data": [
    {
       "type": "comments",
        "id": "1",
        "attributes": {
          "text": "First comment"
        },
        "relationships": {
          "parent": {
            "data": null
          } 
        }
    },
    {
       "type": "comments",
        "id": "2",
        "attributes": {
          "text": "Child comment"
        },
        "relationships": {
          "parent": {
            "data": {
              "type": "comments",
              "id": 1
            }
          } 
        }
    },
  ]
}

My serializer:

class CommentSerializer(ModelSerializer):
    parent = ResourceRelatedField(source='parent_comment', read_only=True)

    class Meta:
        model = Comment
        fields = ('text', 'parent',)

In my ViewSet I have defined resource_name = 'comments', but it is doesn't work for "parent" in relationships. At the present time, "type" of "parent" is "Comment". How can I fix this issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions