Django:从管理视图更改模型字段
我想知道如何更改模型字段的参数,不是在模型初始化期间,而是从模型管理员那里更改。例如,我想根据 get 参数将字段“foo”或“bar”设为可选(想知道 # PSEUDO CODE 位的正确解决方案):
def add_view(self, request, form_url='', extra_context=None):
if request.GET.get('object_type', 'foo') == 'foo':
# PSEUDO CODE:
model.fields.foo.blank = False
model.fields.bar.blank = True
else:
# PSEUDO CODE:
model.fields.foo.blank = True
model.fields.bar.blank = False
return super(FileNodeAdmin, self).add_view(request, form_url, extra_context)
I would like to know how you can change a model's field's parameters, not during model initialisation, but from a model admin. For instance, I would like to make either field "foo" or "bar" optional, according on a get parameter (wondering about the correct solution for the # PSEUDO CODE bit):
def add_view(self, request, form_url='', extra_context=None):
if request.GET.get('object_type', 'foo') == 'foo':
# PSEUDO CODE:
model.fields.foo.blank = False
model.fields.bar.blank = True
else:
# PSEUDO CODE:
model.fields.foo.blank = True
model.fields.bar.blank = False
return super(FileNodeAdmin, self).add_view(request, form_url, extra_context)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会遇到麻烦,因为许多字段的属性都是在数据库级别表示的(即,如果您对具有
null=False
的字段执行manage.pysyncdb
code>,创建数据库字段的 DDL 将具有NOT NULL
)。动态改变数据库约束的行为几乎是不可能的。我处理您所描述的内容的首选方法是在表单级别而不是在模型级别。我的模型将是通用的,并允许所有允许的状态(例如,如果在某些情况下字段可以为空,但在其他情况下不能为空,只需设置
null=True
)。然后,我会动态更改 django.form 实例以更改其验证方式,或者只是在我的视图中手动进行验证。您甚至可能需要一个表单的实例,每个实例都有稍微不同的约束,并根据您的 GET 决定使用哪一个。在伪代码中:You will likely run into trouble since many of the fields' attributes are represented at the database level (i.e., if you do a
manage.py syncdb
with a field that hasnull=False
, the DDL to create the database field will haveNOT NULL
). Dynamically changing the behavior of the database constraints is pretty close to impossible.My prefered method of handling what you are describing would be at the form level and not at the model level. My models would be generic and allow all the allowable states (e.g. if in some cases a field can be null, but not other cases, just set
null=True
). I would then dynamically alter adjango.form
instance to change how it validates, or just do the validation manually in my view. You could even have to instances of a form, each with slightly different constraints and decide which one to use based upon your GET. In pseudo code: