DjangoRest Serializer返回空对象

时间:2016-04-22 08:38:15

标签: python django serialization django-rest-framework

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

model.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='')

Serializer.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 shell中返回空对象时。 此外,我尝试在Box和Type之间进行del依赖,并删除相同的'fields'。

1 个答案:

答案 0 :(得分:4)

需要使用serializers.ModelSerializer ...

它需要看起来像:

class ProductSerializer(serializers.ModelSerializer):
...