【发布时间】:2018-07-05 13:58:57
【问题描述】:
我正在尝试通过 Django Rest Framework 提供嵌套的 json 文件。我一直在阅读不同的方式来嵌套我的序列化程序,但我没有让它工作。
我不知道如何自己创建模型序列化器,而不是直接从我的模型中提取数据...
我的错误:
/listings.json 处的 AttributeError 在尝试 获取序列化程序
TestSerializer上字段coordinates的值。 序列化器字段可能命名不正确并且不匹配任何Test实例上的属性或键。原始异常文本是: “测试”对象没有“坐标”属性。
我的序列化代码:
from rest_framework import serializers
from rentlistings.models import Test
class coordinatesSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = ('latitude', 'longitude')
class propertiesSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = ('price', 'price', 'yields',
'num_floor', 'num_rooms', 'elevator', 'garage',
'balcony_size', 'garden_area', 'parking', 'terass',
'loggia', 'cellar', 'hash_id')
class TestSerializer(serializers.Serializer):
coordinates = coordinatesSerializer(many=True, read_only=True)
properties = propertiesSerializer(many=True, read_only=True)
class Meta:
model = Test
fields = ('coordinates', 'properties')
我的意见.py
from rentlistings.models import Test
from rentlistings.serializers import TestSerializer
from rest_framework import generics
# Create your views here.
class test_list(generics.ListCreateAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer´
使用@aircraft cmets 更正后,我没有收到错误,但API json 中没有包含任何内容:
models.py
from django.db import models
# Create your models here.
class Test(models.Model):
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
hash_id = models.BigIntegerField(primary_key=True, blank=True)
price = models.BigIntegerField(blank=True, null=True)
floor = models.TextField(blank=True, null=True)
garden_area = models.FloatField(blank=True, null=True)
parking = models.TextField(blank=True, null=True)
terass = models.TextField(blank=True, null=True)
loggia = models.TextField(blank=True, null=True)
cellar = models.TextField(blank=True, null=True)
elevator = models.NullBooleanField()
garage = models.TextField(blank=True, null=True)
balcony_size = models.TextField(blank=True, null=True)
date = models.DateTimeField(blank=True, null=True)
last_seen = models.DateTimeField(blank=True, null=True)
num_floor = models.BigIntegerField(blank=True, null=True)
num_rooms = models.BigIntegerField(blank=True, null=True)
yields = models.FloatField(blank=True, null=True)
class Meta:
managed = False
db_table = 'test'
【问题讨论】:
标签: python json django django-rest-framework