1
當我嘗試序列化一些對象時,我得到空對象。 Product.objects有對象DjangoRest Serializer返回空對象
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')
然後,當我使用視圖或殼串行回空對象。 另外我試圖刪除框和類型之間的依賴關係,並刪除相同的'字段'。
正是你在shell做了什麼,你得到了什麼? –
看着你的模型,一個'product'只有一個'box'和一個'type'。你爲什麼用'many = True'的序列化程序。 – AKS
我剛剛嘗試過,從框和類型添加數據仍然無效 – Weit