gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:16:09 26 4
gpt4 key购买 nike

当我使用 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.

我的模型:
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 上的文档了解更多信息。

关于python - 我在 OneToOne 字段中设置了 related_name,但仍然收到 RelatedObjectDoesNotExist 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com