gpt4 book ai didi

python - Django Rest Serializer 返回空对象

转载 作者:行者123 更新时间:2023-11-28 21:47:16 24 4
gpt4 key购买 nike

当我尝试序列化某个对象时,我得到的是空对象。Product.objects 有对象

模型.py

class Product (models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, blank=True, default='')
price = models.IntegerField()
count_of_flowers = models.IntegerField()
type = models.ForeignKey('Type')
box_type = models.ForeignKey('Box', blank=True)
flowers_color = models.CharField(max_length=100, blank=True, default='')

class Type(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, blank=True, default='')

class Box(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, blank=True, default='')

序列化器.py

from rest_framework import serializers
from models import Product, Type, Box

class BoxSerializer(serializers.Serializer):
class Meta:
model = Box
field = ('name')

class TypeSerializer(serializers.Serializer):
class Meta:
model = Type
field = ('name')


class ProductSerializer(serializers.Serializer):
boxes = BoxSerializer(many=True, read_only=True)
types = TypeSerializer(many=True, read_only=True)
class Meta:
model = Product
fields = ('id','name','price','count_of_flowers','boxes','types''flowers_color')

然后,当我使用 View 或在 shell 序列化程序中返回空对象时。我还尝试删除 Box 和 Type 之间的依赖关系并删除相同的“字段”。

最佳答案

需要使用serializers.ModelSerializer...

它需要看起来像:

class ProductSerializer(serializers.ModelSerializer):
...

关于python - Django Rest Serializer 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788957/

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