如何使用 DRF 序列化多对许多 django 模型



如何在输出中获取产品名称和 ID 而不是pro_id和ord_id? 但不是字符串类型。 例如:"名称:某本书"对我来说不是一个有效的选项。我只是在这个上面工作了 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)

产品订购序列化程序

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

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

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

您需要将外键添加到模型 产品顺序 到产品模型,以获得多对多关系,

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
                }
            }
        ]
    }
]
<</div> div class="one_answers">

当我将 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

相关内容

  • 没有找到相关文章