django rest framework序列化相关领域

时间:2017-08-02 08:36:28

标签: django django-rest-framework

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
            )

这里我想列出属于该类别的所有产品变体 我可以这样做,或者我想写方法来获取产品变体细节

1 个答案:

答案 0 :(得分:2)

您可能需要为ProductProductVariation模型编写序列化程序。您无法在ProductVariation模型序列化程序中显示Category个对象,因为CategoryProductVariation模型之间没有直接关系。但您可以尝试为ProductProductVariation模型使用单独的嵌套序列化程序。

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')

您可以将CategorySerializer用于嵌套关系。