我得到'AttrbuteError:'当我尝试使用djangorestframework序列化django模型时,'DeferredAttribute'没有属性'isoformat'' 下面是我试图序列化的模型
class PrimaryRecord(models.Model):
primaryId = models.AutoField(primary_key=True)
primary_track = models.CharField(max_length=30)
title = models.CharField(max_length=255)
start_date = models.DateField()
create_date = models.DateField()
year = models.IntegerField()
我正在使用的序列化程序类位于
之下from rest_framework import serializers
from snippets.models import Assesor, PrimaryRecord, PrimaryAssesor
class PrimaryRecordSerializer(serializers.Serializer):
primary_track = serializers.CharField(max_length=30)
title = serializers.CharField(max_length=255)
start_date = serializers.DateField(format = None)
create_date = serializers.DateField(format = None)
year = serializers.IntegerField()
def create(self, validated_data):
return PrimaryAssesor.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.primary_track = validated_data.get('primary_track', instance.primary_track)
instance.title = validated_data.get('title', instance.title)
instance.start_date = validated_data.get('start_date', instance.start_date)
instance.create_date = validated_data.get('create_date', instance.create_date)
instance.year = validated_data.get('year', instance.year)
instance.save()
return instance
我正在学习djangorestframework的this教程。
我执行以下步骤
p1 = PrimaryRecord(primary_track='P2017-98',title='ABC',start_date=date(2017,6,23),create_date=timezone().now(),year=2017)
p1.save()
serializer = PrimaryRecordSerializer(primaryrecord)
serializer.data # the error occurs here
'AttrbuteError: 'DeferredAttribute' has no attribute 'isoformat''
答案 0 :(得分:0)
初始化primaryrecord
序列化程序时,您使用的是错误的变量p1
而不是PrimaryRecordSerializer
。应该是
serializer = PrimaryRecordSerializer(p1)
不是
serializer = PrimaryRecordSerializer(primaryrecord)