gpt4 book ai didi

python - Django:如果相关对象不存在,则从 OneToOneField 返回 'None'?

转载 作者:IT老高 更新时间:2023-10-28 20:40:42 25 4
gpt4 key购买 nike

我有一个这样的 Django 类:

class Breakfast(m.Model):
# egg = m.OneToOneField(Egg)
...

class Egg(m.Model):
breakfast = m.OneToOneField(Breakfast, related_name="egg")

如果没有与Breakfast相关的Egg,是否可以有breakfast.egg == None

编辑:忘了说:我宁愿不把 related_name 改成 related_name="_egg" 之类的东西,然后有东西喜欢:

@property
def egg(self):
try:
return self.egg
except ...:
return None

因为我在查询中使用名称 egg,我宁愿不必将查询更改为使用 _egg

最佳答案

这个自定义 django 字段将完全满足您的需求:

class SingleRelatedObjectDescriptorReturnsNone(SingleRelatedObjectDescriptor):
def __get__(self, *args, **kwargs):
try:
return super(SingleRelatedObjectDescriptorReturnsNone, self).__get__(*args, **kwargs)
except ObjectDoesNotExist:
return None

class OneToOneOrNoneField(models.OneToOneField):
"""A OneToOneField that returns None if the related object doesn't exist"""
related_accessor_class = SingleRelatedObjectDescriptorReturnsNone

使用它:

class Breakfast(models.Model):
pass
# other fields

class Egg(m.Model):
breakfast = OneToOneOrNoneField(Breakfast, related_name="egg")

breakfast = Breakfast()
assert breakfast.egg == None

关于python - Django:如果相关对象不存在,则从 OneToOneField 返回 'None'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955093/

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