[Answered ]-I want to nest a model into the Serialiazer. Category' object has no attribute 'brand_set'

1👍

Since you specified related_name='category', you obtain the related Brands 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 Brands 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__'

Leave a comment