【问题标题】:How can i serialize manytomany django models using DRF我如何使用 DRF 序列化许多 django 模型
【发布时间】:2017-05-22 02:08:45
【问题描述】:

如何在输出中获取产品名称和 id 而不是 pro_id 和 ord_id?但不是字符串类型。例如:“name:somebook”对我来说不是一个有效的选项。 我只是不间断地工作了 2 天,我想我错过了一些细节,但我找不到它是什么。

我想要的输出

[
  {
"order_id": 1,
"totalquantity": 12,
"totalprice": 56,
"userid": 1,
"customerAddress": "evka1",
"customerPhone": "539",
"trackNo": 12034,
"products": [
  {
    "name": "somebook",
    "id": 1,
    "quantity": 6
  },
  {
    "name": "someotherbook",
    "id": 2,
    "quantity": 6
  }
]
  }
]

我得到的输出

[
  {
"order_id": 1,
"totalquantity": 12,
"totalprice": 56,
"userid": 1,
"customerAddress": "evka1",
"customerPhone": "539",
"trackNo": 12034,
"products": [
  {
    "pro_id": 2,
    "ord_id": 1,
    "quantity": 6
  },
  {
    "pro_id": 3,
    "ord_id": 1,
    "quantity": 6
  }
]
  }
]

订单模式

class Order(models.Model):

    order_id = models.AutoField(primary_key=True)
    totalquantity = models.IntegerField(default=0, null=True)
    totalprice = models.IntegerField(default=0, null=True)
    userid = models.IntegerField(default=0, null=True)
    trackNo = models.IntegerField(default=0, null=True)
    billNo = models.IntegerField(default=0, null=True)
    customerAddress = models.CharField(max_length=30,default="nil", null=True)
    customerPhone = models.CharField(max_length=30,default="nil", null=True)

订单序列化器

class OrderSerializer(serializers.ModelSerializer):
products = ProductOrderSerializer(many=True, read_only=True)

class Meta:
    model = Order
    fields = ('order_id', 'totalquantity', 'totalprice', 'userid', 'customerAddress', 'customerPhone', 'trackNo', 'products')

产品型号

class Product(models.Model):

    name = models.CharField(max_length=30,default="nil", null=True)
    author = models.CharField(max_length=30,default="nil", null=True)
    date = models.DateField(null=True)
    price = models.FloatField(default=0, null=True)
    quantity = models.IntegerField(default=0, null=True)
    soldcount = models.IntegerField(default=0, null=True)
    category = models.CharField(max_length=30,default="nil", null=True)

产品序列化程序

class ProductSerializer(serializers.ModelSerializer):
class Meta:
    model = Product
    fields = ('id', 'name', 'author', 'date', 'price', 'quantity', 'soldcount', 'category')

产品订单模型

class ProductOrder(models.Model):

    pro_id = models.IntegerField(default=0,null=True)
    ord_id = models.ForeignKey(Order, related_name='products')
    quantity = models.IntegerField(default=0, null=True)

ProductOrder 序列化程序

class ProductOrderSerializer(serializers.ModelSerializer):
class Meta:
    model = ProductOrder
    fields = ('pro_id', 'ord_id', 'quantity')

【问题讨论】:

    标签: django web-services serialization


    【解决方案1】:

    使用 django-rest-framework 中的嵌套序列化器可以实现您想要的输出,

    但是,它需要在您的模型中进行一些重构,

    您需要在 ProductOrder 模型中添加一个 ForeignKey 到 Product 模型,以获得多对多关系,

    class ProductOrder(models.Model):
        pro_id = models.ForeinKey(Product, related_name='orders', default=0,null=True)
        ord_id = models.ForeignKey(Order, related_name='products')
        quantity = models.IntegerField(default=0, null=True)
    

    另外,在您的序列化程序中,

    class ProductSerializer(serializers.ModelSerializer):
        class Meta:
            model = Product
            fields = ('name', 'id', 'quantity')
    
    
    class ProductOrderSerializer(serializers.ModelSerializer):
        details = ProductSerializer(source='pro_id', read_only=True)
    
        class Meta:
            model = ProductOrder
            fields = ('details', )
    
    
    class OrderSerializer(serializers.ModelSerializer):
        products = ProductOrderSerializer(many=True, read_only=True)
    
        class Meta:
            model = Order
            fields = ('totalquantity', 'totalprice', 'userid',
                  'trackNo', 'billNo', 'customerAddress', 'customerPhone',
                  'products')
    

    您可以调用 OrderSerializer 并根据需要获取输出,

    def get(self, request, *args, **kwargs):
        orders = Order.objects.all()
        serializer = OrderSerializer(orders, many=True)
        return Response(serializer.data)
    

    输出会是这样的,

    [
        {
            "totalquantity": 0,
            "totalprice": 0,
            "userid": 0,
            "trackNo": 0,
            "billNo": 0,
            "customerAddress": "nil",
            "customerPhone": "nil",
            "products": [
                {
                    "details": {
                        "name": "nil",
                        "id": 1,
                        "quantity": 0
                    }
                },
                {
                    "details": {
                        "name": "nil",
                        "id": 1,
                        "quantity": 0
                    }
                }
            ]
        }
    ]
    

    【讨论】:

      【解决方案2】:

      我将 ProductOrderSerializer 更改为:

      class ProductListingSerializer(serializers.RelatedField):
      
          def to_representation(self, value):
      
              dict={}
              dict['name'] = value.pro_id.name
              dict['id'] = value.pro_id.pk
              dict['quantity'] = value.quantity
              return dict
      

      但我现在处于“我的代码工作我不知道为什么”的情况:D

      【讨论】:

        猜你喜欢
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        相关资源
        最近更新 更多