关于问题。
cursorPatients
/ patients
/etc 是类级变量(static
多变的)。这意味着你没有instance
and properties
在这个级别。粗略地说,你试图使用self
访问对象但对象尚未创建。
如果我理解正确的话你需要改变一些choices
用一个Form property
.
让我们尝试使用以下命令来改变选择__init__
:
class RegisterPatternForm(FlaskForm):
patients = SelectMultipleField('Select the patient',
validators=[Optional()],
choices=[('one', 'one')])
def __init__(self, patients_choices: list = None, *args, **kwargs):
super().__init__(*args, **kwargs)
if patients_choices:
self.patients.choices = patients_choices
RegisterPatternForm() # default choices - [('one', 'one')]
RegisterPatternForm(patients_choices=[('two', 'two')]) # new choices
如你看到的patients
选择正在改变使用constructor
。所以在你的情况下应该是这样的:
class RegisterPatternForm(FlaskForm):
patients = SelectMultipleField('Select the patient',
validators=[Optional()],
choices=[])
def __init__(self, myParam: int, *args, **kwargs):
super().__init__(*args, **kwargs)
self.myParam = myParam
self.patients.choices = self._mongo_mock()
def _mongo_mock(self) -> list:
"""
db = MongoClient('localhost:27017').myDb["coll"]
result = []
for pt in db.find({"field1": self.myParam}).sort([("id", 1)]):
blablabla....
return result
Just an example(I `mocked` mongo)
"""
return [(str(i), str(i)) for i in range(self.myParam)]
form1 = RegisterPatternForm(1)
form2 = RegisterPatternForm(5)
print(form1.patients.choices) # [('0', '0')]
print(form2.patients.choices) # [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')]
希望这可以帮助。