1👍
✅
Since you specified related_name='category'
, you obtain the related Brand
s with:
def get_brands(self, obj):
brands = obj.category.all()
serializer = BrandSerializerNested(brands, many=True)
return serializer.data
But that does not make much sense: the related_name=…
[Django-doc] specifies the name of the relation in reverse so obtaining the Brand
s for a given Category
, you thus can rename these to:
class Brand(models.Model):
category = models.ForeignKey(
Category,
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='brands'
)
#…
and work with a subserializer:
def get_brands(self, obj):
brands = obj.brands.all()
serializer = BrandSerializerNested(brands, many=True)
return serializer.data
or just define BrandSerializerNested
first and use:
class CategorySerializerNested(serializers.ModelSerializer):
brands = serializers.BrandSerializerNested(read_only=True)
class Meta:
model = Category
fields = '__all__'
Source:stackexchange.com