当我使用to_representation时出现错误:

django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:SwitchesPort没有物理服务器。

追溯如下:

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

我的序列化器如下所示:
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,为什么我仍然遇到问题?

最佳答案

if instance.physical_server == None:

这将不起作用,因为如果该实例没有相关的instance.physical_server,则PhysicalServer将引发异常

您可以通过将支票更改为以下内容来解决此问题:
if hasattr(instance, 'physical_server'):

有关更多信息,请参见one-to-one relationships上的文档。

09-25 21:16