父模型(包括子模型)的序列化

时间:2018-06-21 12:48:34

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

我有一些模型-商品模型,Clother和子模型,例如配饰,外套等:

class Commodity(models.Model):
    atribute = models.CharField()

class Clother(models.Model):
    commodity = models.ForeignKey(Commodity)
    clother_atribute = models.CharField()

class Acessories(models.Model):
    clother = models.ForeignKey(Clother)
    acessories_atribute = models.CharField() 

class Outwear(models.Model):
    clother = models.ForeignKey(Clother)
    outwear_atribute = models.CharField()

如何序列化父模型商品以调用所有垂直依赖项。我想查询商品ID并获取所有Clother属性和Acessories或Outwear属性。谢谢!

3 个答案:

答案 0 :(得分:3)

如果我了解您的问题,则可以定义ClotherSerializer。您可以使用link-4在此序列化程序中序列化嵌套对象:

class ClotherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Clother
        fields = ('id', 'acessories_set', 'outwear_set')
        depth = 1

稍后在CommoditySerializer中,您可以使用ClotherSerializer来序列化衣服及其所有关系:

class CommoditySerializer(serializers.ModelSerializer):
    clother_set = ClotherSerializer(many=True)
    class Meta:
        model = Commodity
        fields = ('id', 'clother_set')

答案 1 :(得分:2)

您可以为此使用drf-writable-nested [GitHub]软件包,并在序列化程序中指定如何序列化某些字段。通过使用另一个 serializer ,您可以通过调用以下子代的序列化器来指定要序列化的序列:

class CommoditySerializer(WritableNestedModelSerializer):
    clother_set = ClotherSerializer(many=True)

    class Meta:
        model = Commodity
        fields = ("atribute", 'clother_set')


class ClotherSerializer(WritableNestedModelSerializer):

    class Meta:
        model = Clother
        fields = ("clother_atribute",)

当然,您可以添加更多此类关系,例如为Acessories指定Clother

我建议您查看GitHub页面,并将其用作自己的序列化器的模板。

答案 2 :(得分:1)

或者,也可以使用SerializerMethodFieldhttp://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

来实现。
class ClotherSerializer(serializers.ModelSerializer):
    """
    Serializer for Clother data model.
    """
    acessories = serializers.SerializerMethodField()
    outwears = serializers.SerializerMethodField()

    class Meta:
        model = Clother
        fields = ('id', 'acessories', 'outwears')

    def get_acessories(self, clother):
        return AcessoriesSerializer(clother.acessories_set.all(), many=True).data

    def get_outwears(self, clother):
        return OutwearSerializer(clother.outwear_set.all(), many=True).data


class CommoditySerializer(serializers.ModelSerializer):
    """
    Serializer for Commodity data model.
    """
    clother = serializers.SerializerMethodField()

    class Meta:
        model = Commodity
        fields = ('id', 'clother')

    def get_clother(self, commodity):
        return ClotherSerializer(commodity.clother_set.all(), many=True).data