我在OneToOne字段中设置了相关的_名称,但是仍然得到relatedObjectDoesNotex

2024-04-25 16:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用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,为什么我仍然得到这个问题?在


Tags: todjangoinstanceinselffieldsdbserver
1条回答
网友
1楼 · 发布于 2024-04-25 16:52:49

按照以下顺序执行这些步骤:

  1. 一般来说,尽量避免static,因为这与OOP原则无关
  2. 如果坚持使用static,则无论访问方式如何,字段必须为final
  3. 首选getters而不是public可见性修饰符

但是是的,这取决于你的喜好

相关问题 更多 >