更新时间:2023-12-02 08:45:40
如果他们向字段添加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