当我使用to_representation
时,我得到错误:
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server.
回溯如下:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework/serializers.py", line 656, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Users/asd/Desktop/xxx/api/serializers.py", line 256, in to_representation
if instance.physical_server == None:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 407, in __get__
self.related.get_accessor_name()
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server.
我的模型:
^{pr2}$我的序列化程序如下:
class SwitchesPortSerializer(ModelSerializer):
"""
switches port
"""
class Meta:
model = SwitchesPort
fields = "__all__"
extra_kwargs = {
"vlaned_network":{"read_only":True}
}
def to_representation(self, instance):
serialized_data = super(SwitchesPortSerializer, self).to_representation(instance)
if instance.physical_server == None: # there syas the error
serialized_data['is_connected'] = True
return serialized_data
你看,OneToOne字段有related_name
,为什么我仍然得到这个问题?在
这行不通,因为时引发异常
instance.physical_server
将在该实例没有相关的^{您可以通过将支票更改为:
^{pr2}$有关详细信息,请参阅one-to-one relationships上的文档。在
相关问题 更多 >
编程相关推荐