django rest framework:包含相同路径中的相关模型字段

时间:2017-05-26 10:41:55

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

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
       model = Product
       fields = ('id','product_id','sku', 'title','price','images')

class WishListSerializer(serializers.ModelSerializer):
      product = ProductSerializer()

      class Meta:
        model = WishList
        fields = ('wishlist_id','product',)

我有两个序列化程序。愿望清单和产品。我想列出所有愿望清单产品。它现在工作正常。但是产品细节是在"产品"关键元素。我可以删除该产品密钥,并显示产品详细信息以及wishlist_id吗?

目前的结果:

 {
      "count": 2,
      "next": null,
      "previous": null,
      "results": [
        {
          "wishlist_id":1,
          "product": {
            "id": 1460,
            "product_id": "04396134-3c90-ea7b-24ba-1fb0db11dbe5",
            "sku": "bb4sd817",
            "title": "Trinity Belt",

          }
        },
        {
          "wishlist_id":2,
          "product": {
            "id": 596,
            "product_id": "52588d22-a62c-779b-8044-0f8d9892e853",
            "sku": "ml346",
            "title": "Martina Liana",
          }
        }
      ]
    }

预期结果:

    {
      "count": 2,
      "next": null,
      "previous": null,
      "results": [
        {
          "wishlist_id":1,
          "id": 1460,
          "product_id": "04396134-3c90-ea7b-24ba-1fb0db11dbe5",
          "sku": "bb4sd817",
          "title": "Trinity Belt",

        },
        {
          "wishlist_id":2,
          "id": 596,
          "product_id": "52588d22-a62c-779b-8044-0f8d9892e853",
          "sku": "ml346",
          "title": "Martina Liana",
        }
      ]
    }

2 个答案:

答案 0 :(得分:0)

这是一种非常糟糕的做法,您需要付出很多努力才能实现序列化和反序列化,尤其是在Post,Update等情况下。 我可以想到两种方式。 1)您可以在WishListSerializer中使用缺少的字段作为SerializerMethodField 示例

product_id = serializers.SerializerMethodField()

 def get_product_id(self, obj):
        return obj.get_product().product_id

2)

class WishListSerializer(serializers.HyperlinkedModelSerializer):
    product_id = serializers.CharField(source='product.product_id')
    .......

    class Meta:
        model = WishList
        fields = (product_id, ......)

答案 1 :(得分:0)

您可以“嵌套” to_representation中的项目 https://www.django-rest-framework.org/api-guide/fields/#custom-fields

上的文档
...
class WishListSerializer(serializers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = WishList
        fields = ('wishlist_id', 'product',)

    # add 
    def to_representation(self, instance):
        data = super().to_representation(instance)
        flat_data = dict(wishlist_id=data['wishlist_id'], **data['product']) # construct (new dict) flat data 
        # or you could restructure same dict: data.update(data.pop('product')) 
        return flat_data