Django Rest Framework以一对多关系获取其他相关字段

时间:2018-09-04 12:05:55

标签: django django-models django-rest-framework many-to-many

这是产品具有多种尺寸且具有多对多关系的问题

产品

\r

尺寸

|-------|---------|
|   ID  |  Title  |
|-------|---------|

调整大小

|-------|---------|
|   ID  |  Title  |
|-------|---------|

我设法使用Django Rest Framework在产品api中获取尺寸,但我也不知道如何获取库存信息。 这是我的代码

|------|--------------|-----------|---------|
|  ID  |  Product ID  |  Size ID  |  Stock  |
|------|--------------|-----------|---------|

在此问题上的任何帮助,我将不胜感激

模型

class SizeSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'title',
        )
        model = Size



class ProductsSerializer(serializers.ModelSerializer):
    sizes = SizeSerializer(many=True)

    class Meta:
        fields = (
            'url',
            'id',
            'title',
            "sizes",
        )
        model = Products

2 个答案:

答案 0 :(得分:1)

可以尝试一下吗?也许行得通

class ProductsSerializer(serializers.ModelSerializer):
    sizes = SizeSerializer(many=True)
    stock = serializers.SerializerMethodField()

    def get_stock(self, obj):
         return[(x.stock, x.size) for x in SizeThrough.objects.filter(product=obj)]

    class Meta:
        fields = (
        'url',
        'id',
        'title',
        "sizes",
        "stock",
    )
        model = Products

答案 1 :(得分:1)

您应该通过Size得到SizeThrough(您正尝试相反的做法):

class SizeSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'title',
        )
        model = Size


class SizeThroughSerializer(serializers.ModelSerializer):
    size = SizeSerializer()
    class Meta:
        fields = (
            'stock',
            'size',
        )
        model = SizeThrough


class ProductsSerializer(serializers.ModelSerializer):
    sizes_info = SizeThroughSerializer(source='sizethrough_set', many=True)

    class Meta:
        fields = (
            'url',
            'id',
            'title',
            "sizes_info",
        )
        model = Products