我在OneToOne字段中设置了related_name,但仍然收到RelatedObjectDoesNotExist错误

时间:2018-01-04 11:47:30

标签: python django django-rest-framework

当我使用to_representation时出现错误:

  

django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:SwitchesPort没有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.

我的模特:

class SwitchesPort(models.Model):
    """
    交换机接口
    """
    ...
    switches = models.ForeignKey(to=Switches, on_delete=models.CASCADE,related_name="switchesports", help_text="所属交换机")
    vlanedipv4networkgroup = models.ForeignKey(
        to=VlanedIPv4NetworkGroup, # 初始化之后的
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="switchesports",
        help_text="所关联的vlaned组")

    network_speed = models.IntegerField(default=10, help_text="交换机控制网络流量速度")

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class PhysicalServer(models.Model):
    """
    physical_server
    """
    ...

    switchesport = models.OneToOneField(to=SwitchesPort, related_name="physical_server", on_delete=models.DO_NOTHING, help_text="所属交换机接口",
                                     null=True)   

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

My Serializer如下:

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 Field有related_name,为什么我仍然会遇到这个问题?

1 个答案:

答案 0 :(得分:3)

if instance.physical_server == None:

这不会起作用,因为如果该实例没有相关的instance.physical_server

PhysicalServer会引发异常

您可以将支票更改为:

来解决问题
if hasattr(instance, 'physical_server'):

有关详细信息,请参阅one-to-one relationships上的文档。