我试图通过Django Rest Framework提供嵌套的json文件。我一直在阅读不同的方式来嵌套我的序列化器,但我没有让它工作。
我不知道如何自己创建一个modelserializer,而不是直接从我的模型中提取数据......
我的错误:
/listings.json中的AttributeError尝试时遇到AttributeError 获取序列化程序
coordinates
上的字段TestSerializer
的值。 序列化程序字段可能名称不正确,并且不匹配任何字段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')
我的views.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评论进行更正后,我没有收到任何错误,但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'
答案 0 :(得分:0)
在你的TestSerializer
中,你应该添加下面的参数:
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')