序列化器处理嵌套对象

jas*_*son 8 django django-rest-framework

使用Django REST 框架,我在下面有以下序列化程序。我想将(嵌套的)相关对象(ProductCatSerializer)添加到 ProductSerializer。我尝试了以下....

class ProductCatSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductCat
        fields = ('id', 'title')

class ProductSerializer(serializers.ModelSerializer):
    """
    Serializing the Product instances into representations.
    """
    ProductCat = ProductCatSerializer()

    class Meta:
        model = Product
        fields = ('id', 'title', 'description', 'price',)
Run Code Online (Sandbox Code Playgroud)

所以我想要发生的是 Products 显示其嵌套在结果中的相关类别。

谢谢你。

更新:

使用 depth = 2 选项(感谢 Nandeep Mali )我现在得到嵌套值,但它们只显示使用 ID 而不是 keyparis 像其余的 json 请求(见下面的类别)。它几乎是正确的。

"results": [
        {
            "id": 1, 
            "title": "test ", 
            "description": "test", 
            "price": "2.99", 
            "product_url": "222", 
            "product_ref": "222", 
            "active": true, 
            "created": "2013-02-15T15:49:28Z", 
            "modified": "2013-02-17T13:05:28Z", 
            "category": [
                1, 
                2
            ], 
Run Code Online (Sandbox Code Playgroud)

Tom*_*tie 5

您的示例几乎是正确的,除了您应该调用字段“productcat”(或调用任何模型关系,但没有 CamelCase),并将其添加到您的字段中。

class ProductCatSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductCat
        fields = ('id', 'title')

class ProductSerializer(serializers.ModelSerializer):
    """
    Serializing the Product instances into representations.
    """
    productcat = ProductCatSerializer()

    class Meta:
        model = Product
        fields = ('id', 'title', 'description', 'price', 'productcat')
Run Code Online (Sandbox Code Playgroud)

  • 完美,我正在学习,慢慢地,但是学习!再次感谢汤姆。 (2认同)