gpt4 book ai didi

python - 如何在具有多对多关系的 Django 中反向序列化

转载 作者:行者123 更新时间:2023-12-03 23:13:21 26 4
gpt4 key购买 nike

我第一次做了 category crud,然后 productcategory 具有多对多关系的 crud .models.py ( category ):

class Category(models.Model):
name = models.CharField(max_length=191, blank=False, null=False)
description = models.TextField(blank=True, null=True)
models.py ( product ):
class Product(models.Model):
product_code = models.CharField(max_length=191, blank=False, null=False)
name = models.CharField(max_length=191, blank=False, null=False)
description = models.TextField(blank=False, null=False)
price = models.DecimalField(max_digits=19, decimal_places=2)
photo = models.ImageField(upload_to='pictures/products/', max_length=255, null=False, blank=False)
category = models.name = models.ManyToManyField(Category)

如何实现以下结果:
  {
"categories": [
{
"id": 1,
"name": "Indoor Muscle Training",
"description": null,
"products":{
"name":"product_name",
"code":"product_code"
}
},
{
"id": 2,
"name": "Outdoor Muscle Training",
"description": null,
"products":{
"name":"product_name",
"code":"product_code"
}
}
]
}

最佳答案

使用 serializer-method字段可以是这种情况下的一个选项。我们的目标是获得 product信息来自 category序列化器。所以对于这个

class CategorySerializer(serializers.ModelSerializer):
products = serializers.SerializerMethodField()

class Meta:
model = Category
fields = ('') # add relative fields

def get_products(self, obj):
products = obj.product_set.all() # will return product query set associate with this category
response = ProductSerializer(products, many=True).data
return response

关于python - 如何在具有多对多关系的 Django 中反向序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com