In formsets.py, you find this code snippet
在formsets.py中,您可以找到此代码段
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
...
self.prefix = prefix or self.get_default_prefix() # Note the self.get_default_prefix
...
...
@classmethod # Note the @classmethod
def get_default_prefix(cls):
return 'form'
Why is get_default_prefix declared this way and then called with self.? Is there something gained by doing it this way? get_default_prefix
has another definition in BaseInlineFormSet (forms/models.py)
为什么get_default_prefix以这种方式声明,然后用self调用。通过这种方式获得了什么? get_default_prefix在BaseInlineFormSet中有另一个定义(forms / models.py)
class BaseInlineFormSet(BaseModelFormSet):
...
@classmethod
def get_default_prefix(cls):
from django.db.models.fields.related import RelatedObject
return RelatedObject(cls.fk.rel.to, cls.model, cls.fk).get_accessor_name().replace('+','')
and another in BaseGenericInlineFormset
again using the @classmethod, so it doesn't appear to be a typo. I just don't understand why it would be done this way and then called with self.
另一个在BaseGenericInlineFormset中再次使用@classmethod,所以它似乎不是一个错字。我只是不明白为什么会以这种方式完成然后用自己调用。
The only clue I see (which I don't understand) is that the admin seems to call it with FormSet.get_default_prefix()
我看到的唯一线索(我不明白)是管理员似乎用FormSet.get_default_prefix()调用它
I'm wondering if there is something I'm just not understanding about python.
我想知道是否有些东西我只是不了解python。
1 个解决方案
#1
1
Calling a class method from an instance is perfectly legal, as you can see in the code. A related * post said there was no benefit, (and it is bad practice) to call from an instance; because if you are only calling from instance your method should probably not be a classmethod
.
从代码中调用类方法是完全合法的,正如您在代码中看到的那样。一个相关的*帖子说从一个实例调用没有任何好处(并且这是不好的做法);因为如果你只是从实例调用你的方法可能不应该是一个类方法。
I think you answer your own question, though. If django is calling FormSet.get_default_prefix()
from somewhere, then they probably didn't want to instantiate a formset object
不过,我想你回答了自己的问题。如果django从某个地方调用FormSet.get_default_prefix(),那么他们可能不想实例化一个formset对象
#1
1
Calling a class method from an instance is perfectly legal, as you can see in the code. A related * post said there was no benefit, (and it is bad practice) to call from an instance; because if you are only calling from instance your method should probably not be a classmethod
.
从代码中调用类方法是完全合法的,正如您在代码中看到的那样。一个相关的*帖子说从一个实例调用没有任何好处(并且这是不好的做法);因为如果你只是从实例调用你的方法可能不应该是一个类方法。
I think you answer your own question, though. If django is calling FormSet.get_default_prefix()
from somewhere, then they probably didn't want to instantiate a formset object
不过,我想你回答了自己的问题。如果django从某个地方调用FormSet.get_default_prefix(),那么他们可能不想实例化一个formset对象