问题描述
我想在model.Field
基类中添加额外的参数以后使用而无需在Form
或ModelForm
类中再次定义字段的额外选项.
I wanted to add extra argument to model.Field
base class touse later without defining field's extra options again in Form
or ModelForm
class.
然后我可以添加额外的参数:
And I can add extra argument with:
class Poll(models.Model):
question = models.CharField(max_length=200,
extra= { 'widget': 'xw',
'admin_list_order': 3 })
pub_date = models.DateTimeField('date published')
我可以通过以下方式访问额外的arg:
I can access extra arg with:
(InteractiveConsole)
>>> from polls.models import Poll
>>> Poll._meta.fields[1].extra
{'widget': 'xw', 'admin_list_order': 3}
>>>
这是添加额外参数的Python适当方法吗?
Is this an appropriate, Pythonic way to add an extra argument?
from django.db import models
# save old __init__ function of Field class
__oInit = models.Field.__init__
# define a new one to accept 'extra' arg
def __xinit__(self, *args, **kwargs):
#chek if extra arg exist
if kwargs.has_key('extra'):
self.extra = kwargs.pop('extra')
#call real __init__
__oInit(self, *args, **kwargs)
# replace init with new one
models.Field.__init__ = __xinit__
推荐答案
如果他们向字段添加extra
自变量,则可能会中断.而且一般不建议使用 monkeypatches .您可以通过向Field
基类中添加方法来走一条更安全的路线:
This could break if they ever add an extra
argument to a field. And monkeypatches are discouraged in general. You could go a safer route by adding a method to the Field
base class:
def set_extra(self, **kwargs):
self.extra = kwargs
return self
models.Field.set_extra = set_extra
然后像这样定义模型:
class Poll(models.Model):
question = models.CharField(max_length=200).set_extra(
widget='xw', admin_list_order=3)
has_key
被认为是 unpythonic ,检查密钥是否存在的首选方法是:
has_key
is considered unpythonic, preferred way to check for key presence is:
if 'extra' in kwargs:
self.extra = kwargs.pop('extra')
更多的 pythonic 会尝试并捕获失败:
More pythonic would be just trying it and catching failure:
try:
self.extra = kwargs.pop('extra')
except KeyError:
pass
这篇关于Django,模型字段定义的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!