Django:知道属性是否是默认值

时间:2021-01-19 18:37:09

How can you know if a value is the default value for a Model's property.

如何知道某个值是否为Model属性的默认值。

For example

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.

我试着在文档中挖掘,但没有看到任何东西。

2 个解决方案

#1


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.

Django中的默认值与SQL默认值不同 - 它仅供管理员在新对象创建时自动填充表单字段。

If you want to compare something to value defined as default you have to define it somewhere else (i.e. in settings.py). Like:

如果要将某些内容与定义为默认值的值进行比较,则必须在其他位置(即在settings.py中)将其定义。喜欢:

class MyModel(models.Model):
    ...
    my_field = models.IntegerField(default=settings.INT_DEFAULT)

The default value is stored in MyModel._meta._fields()[field_creation_index].default but be aware that this is digging in internals.

默认值存储在MyModel._meta._fields()[field_creation_index] .default中,但要注意这是在内部挖掘。

#2


You can't get it from the property itself, you have to go via the model options under model._meta.

你不能从房产本身获得它,你必须通过model._meta下的模型选项。

a._meta.get_field_by_name('image')[0].get_default()

#1


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.

Django中的默认值与SQL默认值不同 - 它仅供管理员在新对象创建时自动填充表单字段。

If you want to compare something to value defined as default you have to define it somewhere else (i.e. in settings.py). Like:

如果要将某些内容与定义为默认值的值进行比较,则必须在其他位置(即在settings.py中)将其定义。喜欢:

class MyModel(models.Model):
    ...
    my_field = models.IntegerField(default=settings.INT_DEFAULT)

The default value is stored in MyModel._meta._fields()[field_creation_index].default but be aware that this is digging in internals.

默认值存储在MyModel._meta._fields()[field_creation_index] .default中,但要注意这是在内部挖掘。

#2


You can't get it from the property itself, you have to go via the model options under model._meta.

你不能从房产本身获得它,你必须通过model._meta下的模型选项。

a._meta.get_field_by_name('image')[0].get_default()