检查非可空字段是否为空(Django)

时间:2022-05-08 22:50:42

I wanted to write some code like this:

我想写一些像这样的代码:

class SomeModel(models.Model):

    field = models.ForeignKey(SomeOtherModel)

    def __init__(self, *args, **kwargs):
        super(SomeModel, self).__init__(*args, **kwargs)
        if self.field is None:
            self.field = SomeOtherModel()

    ...

However this raises self.field.rel.to.DoesNotExist. The Django code is very clear on that:

然而,这引发了self.field.rel.to.DoesNotExist。 Django代码非常明确:

class ReverseSingleRelatedObjectDescriptor(object):

    def __get__(self, instance, instance_type=None):

        ...

        if val is None:
            # If NULL is an allowed value, return it.
            if self.field.null:
                return None
            raise self.field.rel.to.DoesNotExist

I'm almost certain this issue has been raised before, however somehow I wasn't able to find anything that would match that particular usecase. An obvious workaround would be of course to make the field nullable however as far as I understand that would actually have an effect on the database schema, also I like the integrity checks Django offers. Another one would be to catch the exception and handle it appropriately. However this adds a lot of boilerplate code. Especially when there are multiple fields like that (a separate try...except block for each one of them - now that's ugly). What would you suggest?

我几乎可以肯定这个问题之前已经提出过,但不知怎的,我无法找到任何与该特定用例相匹配的东西。一个明显的解决方法当然是使字段可以为空,但据我所知,这实际上会对数据库模式产生影响,我也喜欢Django提供的完整性检查。另一个是捕获异常并适当处理它。然而,这增加了许多样板代码。特别是当有多个像这样的字段时(一个单独的尝试...除了每个字段的块 - 现在这很难看)。你会建议什么?

EDIT: Another thing - I could use initial however this is quite limited when it comes to foreign keys. I do not always know the kind of default that I would like to have at the moment of creation. I will however know it at the initialization phase. Moreover it could then be dependent on the values of the other fields.

编辑:另一件事 - 我可以使用初始但是当涉及到外键时这是非常有限的。我并不总是知道在创作时我想要的默认类型。但是我会在初始化阶段知道它。而且它可能依赖于其他字段的值。

2 个解决方案

#1


10  

Check if it has the attribute set -

检查它是否具有属性集 -

if hasattr(self, 'field', False)

#2


0  

proper way to refer a field in form is like this:
self.fields['myfield']
so, in your case, the null check should go like this
self.fields['myfield'].value is None

在表单中引用字段的正确方法是这样的:self.fields ['myfield']所以,在你的情况下,null检查应该像这个self.fields ['myfield']。值是None

on the other note, don't use reserved/near to reserved words like 'field' for naming your fields.

另一方面,不要使用保留/接近保留字,如“字段”来命名字段。

#1


10  

Check if it has the attribute set -

检查它是否具有属性集 -

if hasattr(self, 'field', False)

#2


0  

proper way to refer a field in form is like this:
self.fields['myfield']
so, in your case, the null check should go like this
self.fields['myfield'].value is None

在表单中引用字段的正确方法是这样的:self.fields ['myfield']所以,在你的情况下,null检查应该像这个self.fields ['myfield']。值是None

on the other note, don't use reserved/near to reserved words like 'field' for naming your fields.

另一方面,不要使用保留/接近保留字,如“字段”来命名字段。