0

I'm using Django and Django-rest-framework, and I have the next Model and Serializer:

class Category(models.Model):
    id_category = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
    name = models.TextField(null=False)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id_category', 'name', 'parent')

Now, I want to make a query like Category.objects.filter(parent=None) that returns something like this:

[
  {
    "id_category": "UUID",
    "name": "Father",
    "childrens": [
      {
        "id_category": "UUID",
        "name": "Son",
        "childrens": [
          {
            "id_category": "UUID",
            "name": "Grandson"
          }
        ]
      }
    ]
  },
  {
    "id_category": "UUID",
    "name": "Other"
  }
]

As you see, a Category could have one father and many children. Need help to make this query, because I don't know how do that.

1 Answer 1

1

You can write additional serializer for child category:

class ChildrenSerializer(serializers.ModelSerializer):

    class Meta:
         model = Category
         fields = ('id_category', 'name', 'parent')

class CategorySerializer(serializers.ModelSerializer):
    children = ChildrenSerializer(many=True)

    class Meta:
        model = Category
        fields = ('id_category', 'name', 'parent', 'children')

You could also show nested models with depth option:

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        depth = 1
        fields = ('id_category', 'name', 'parent', 'children')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.