Python DRF@property field serializer在尝试获取序列化程序Y上的字段X的值时获取了AttributeError
我正在使用django rest框架序列化和更新@property字段,但出现了以下错误:Python DRF@property field serializer在尝试获取序列化程序Y上的字段X的值时获取了AttributeError,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我正在使用django rest框架序列化和更新@property字段,但出现了以下错误: AttributeError: Got AttributeError when attempting to get a value for field `template` on serializer `PublicationSerializer`. The serializer field might be named incorrectly and not match any attribute or
AttributeError: Got AttributeError when attempting to get a value for field `template` on serializer `PublicationSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Publication` instance.
Original exception text was: 'NoneType' object has no attribute 'template'.
我有以下型号:
class Publication(models.Model):
@property
def template(self):
return self.apps.first().template
class App(models.Model):
publication = models.ForeignKey(Publication, related_name='apps')
template = models.ForeignKey(Template, blank=True, null=True)
class Template(models.Model):
name = models.CharField(_('Public name'), max_length=255, db_column='nome')
和以下序列化程序:
class PublicationSerializer(serializers.ModelSerializer):
template = TemplateSerializer(read_only=False)
class Meta:
model = models.Publication
fields = ('template',)
def update(self, instance, validated_data):
template_data = validated_data.pop('template', None)
instance = super().update(instance, validated_data)
if template_data:
instance.apps.all().update(template__id=template_data['id'])
return instance
当我使用GET方法查看出版物,并且我的Publication.apps为空,并且当我尝试使用POST方法时,我收到一个空的orderedict()
对象时,会发生此错误
这看起来像是当我的字段为空时,DRF无法发现字段类型,当我尝试发布序列化程序时,序列化程序也无法正常工作…看起来像是您尝试使用的出版物,但没有相关的应用程序。这就是为什么
self.apps.first()
returnNone
和self.apps.first().template
引发异常。尝试将属性更改为:
@property
def template(self):
return getattr(self.apps.first(), 'template', None)