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

时间:2017-05-21 13:36:39

标签: django web-services serialization

如何在输出中获取产品名称和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')

ProductOrder模型

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 Serializer

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用django-rest-framework中的嵌套序列化程序实现所需的输出,

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

为了获得ManyToMany关系,您需要向产品模型添加一个ForeignKey到ProductOrder模型,

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
                }
            }
        ]
    }
]