问题描述
如何知道值是模型属性的默认值。
How can you know if a value is the default value for a Model's property.
例如
class Alias(models.Model) :
image = models.ImageField(upload_to='alias', default='/media/alias-default.png')
a = Alias.get("123")
# this doesn't work
if a.image == a.image.default :
pass
# nor this
if a.image == Alias.image.default :
pass
我尝试挖掘文档,但没有看到任何东西。 >
I tried digging in the docs, but didn't see anything.
推荐答案
Django中的默认值
与SQL默认值不同 - 管理员自动填写新对象创建的表单域。
The default
in Django is not the same as SQL default - it's there merely for admin to auto-fill the form field on new object creation.
如果要比较某些值定义为默认值
你必须在别的地方定义它(即在 settings.py
)。喜欢:
If you want to compare something to value defined as default
you have to define it somewhere else (i.e. in settings.py
). Like:
class MyModel(models.Model):
...
my_field = models.IntegerField(default=settings.INT_DEFAULT)
默认值
value存储在 MyModel._meta._fields()[field_creation_index] .default
中,但请注意,这是在内部挖掘。
The default
value is stored in MyModel._meta._fields()[field_creation_index].default
but be aware that this is digging in internals.
这篇关于Django:知道属性是否为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!