小编Igo*_*gor的帖子

为什么在python 2.7和python 3.4性能中创建类之间存在差异

from timeit import Timer as T

def calc(n):
    return T("class CLS(object): pass").timeit(n)

print(calc(90000))
print(calc(90000))
print(calc(90000))

# python3.4
1.1714721370008192
1.0723806529986177
1.111804607000522

# python2.7
15.7533519268
16.7191421986
16.8397979736
Run Code Online (Sandbox Code Playgroud)

为什么使用不同版本的python在类创建时间上有这么大的差异?在同一台机器上测试:

  • i5-3450 CPU @ 3.10GHz
  • 8gb ram

python performance python-2.7 python-3.x

9
推荐指数
1
解决办法
305
查看次数

Django modelform根据其他字段选择删除"required"属性

我有几个字段的ModelForm.有些字段是必需的,有些则不是.此外,我选择具有不同选择的字段,并且我希望根据此选择字段选择使某些字段"必需".

我尝试了Form的clean()方法

def clean(self):
    cleaned_data = self.cleaned_data
    some_field = cleaned_data.get("some_field")
    if some_field == 'some_value':
          self.fields['other_field'].required = False
    return cleaned_data
Run Code Online (Sandbox Code Playgroud)

但它不起作用

django django-models django-forms

7
推荐指数
1
解决办法
5792
查看次数

如何使用Django在数据库中插入NULL

我在Django中插入NULL时遇到问题.我的意思是我不知道该怎么做.

我有函数,让我们调用它find_position,然后我在模型中有字段position(IntegerField,null = True,blank = True).这个函数检查一些html代码,如果它与一些正则表达式匹配,它返回整数,但如果它没有找到 - 必须返回NULL或None或我可以放在数据库中的东西.

 def find_position(self, to_find, something): 
   ...
       if re.search(to_find, something): 
           return i + (page * 10) + 1 
    return NULL # or what i have to return here?
Run Code Online (Sandbox Code Playgroud)

我有这个:

_position = find_position(to_find, something)
p = Result(position=_position, ...)
r.save()
Run Code Online (Sandbox Code Playgroud)

以前我用CharField for position,如果找不到结果,则返回' - '.但我在计算总结果时遇到了问题,比如position__lte = 10(因为它不是,integer而且它与数字和字符串搞混了-.

我该怎么办?

database django integer nullable django-models

1
推荐指数
1
解决办法
5657
查看次数