如何在Django中以JSON格式返回数据

时间:2017-12-31 15:58:37

标签: python django django-rest-framework

我想以JSON格式返回一些数据,我创建了serializers.py

class LocationSerializers(serializers.EmbeddedDocumentSerializer):
  class Meta:
    model = location
    fields = '__all__'

class ProductsSerializers(serializers.DocumentSerializer):
  location = LocationSerializers(many=True)
  class Meta:
    model = products
    fields = ('picture', 'name', 'email', 'city', 'location')

Models.py

class location(EmbeddedDocument):
  type = fields.StringField()
  coordinates = fields.ListField(FloatField())

class products(Document):
  picture = fields.StringField()
  name = fields.StringField()
  email = fields.StringField()
  city = fields.StringField()
  location = fields.EmbeddedDocumentField('location')

和views.py

def get(self, request):
    prd = products.objects.all()
    data = ProductsSerializers(prd,many=True)
    return Response(data.data)

当我退回一件产品时,它工作但我想要归还所有不起作用 我不明白错误

The fields "{'_ref'}" do not exist on the document "location"

1 个答案:

答案 0 :(得分:0)

我找到解决方案只是将EmbeddedDocumentSerializer更改为EmbeddedDocumentSerializer

class location(EmbeddedDocument):

class Location(DynamicDocument):
  

使用DynamicDocuments,您可以保存任何额外的属性,而无需在模型上明确定义