0

models.py

class Category(models.Model):
    name = models.CharField(max_length=128)


class Product(models.Model):
    category = models.ManyToManyField(Category, related_name="category")
    name = models.CharField(max_length=128)


class ProductVariation(models.Model):
    product = models.ForeignKey(Product, related_name="product")
    name = models.CharField(max_length=128)

serializers.py

class ProductVariantSerializer(serializers.HyperlinkedModelSerializer)
    class Meta:
        model = ProductVariation

        fields = (
            "name",
            )

class CategoryDetailSerializer(serializers.Modelserializer):

    product_variant = PromotionVariantSerializer(many=True)
    class Meta:
        model = Category
        fields =(
            "name",
            "product_variant" #how can i do this
            )

here i want to list all the product variant that belongs to the category.
can i do this way or i want to write methods to get the product variant details

1 Answer 1

3

You may need to write serializers for Product and ProductVariation models. You can't display the ProductVariation objects right in the Category model serializer, as there is no direct relation between Category and ProductVariation models. But you could try may be using separate nested serializers for Product and ProductVariation models.

class ProductVariantSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductVariation
        fields = ("name", )

class ProductSerializer(serializers.ModelSerializer):
    variants = ProductVariantSerializer(source='product', many=True, read_only=True)
    class Meta:
        model = Product
        fields = ('name', 'variants')

class CategorySerializer(serializers.ModelSerializer):
    products = ProductSerializer(source='category', many=True, read_only=True)
    class Meta:
        model = Category
        fields = ('name', 'products')

You could use the CategorySerializer for nested relationships.

Sign up to request clarification or add additional context in comments.

2 Comments

how can i display only the variant not the products.
Then, you may need to use serializer method field or such approach, because Category and ProductVariation are related only through Product model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.