Wei*_*eit 2 python django serialization django-rest-framework
当我尝试序列化某些对象时,我得到了空对象。产品。对象有对象
模型
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='')
Run Code Online (Sandbox Code Playgroud)
序列化器
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')
Run Code Online (Sandbox Code Playgroud)
然后,当我使用view或在shell中使用Serializer返回空对象。我也尝试删除Box和Type之间的依赖关系,并删除了相同的“字段”。
需要使用serializers.ModelSerializer...
它需要看起来像:
class ProductSerializer(serializers.ModelSerializer):
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |