Weit Weit - 7 months ago 27
Python Question

DjangoRest Serializer returns empty object

When I try to serialize some object I get empty object.
Product.objects have object

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')


And then, when I use view or in shell Serializer return empty object.
Also I tried to del dependency between Box and Type and deleted the same 'fields'.

Answer

Need to use serializers.ModelSerializer...

It needs to look like:

class ProductSerializer(serializers.ModelSerializer):
...