这是我获得所需价值的唯一方法:
User1.types1.r_q2.label
我想通过用变量替换field name
和textChoices
使其动态。我该怎么办?
Models.py:
class User1(models.Model):
class r_q1(models.TextChoices):
r_q2 = 'r_q2', 'second question'
r_q3 = 'r_q3', 'third question'
t_greeting = 't_greeting', 't_greeting'
f_passport = 'f_passport', 'Contact with a human f_passport'
r_q1 = models.CharField (
'How can I help you, today?1',
max_length=200,
choices=r_q1.choices, blank=True, null=False
)
这可行,但是当我仅替换fieldname
时:
User1.types1[x].label
当我以textChoices
的名称进行操作时,它不起作用并引发错误:
User1[y][x].label
错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ModelBase' object is not subscriptable
旁注:我的models.py中有很多textChoices。我没有包括它们,因为它们在这里并不重要。
答案 0 :(得分:1)
我通过使用getattr()
使它正常工作。
getattr(User1, 'types1')['r_q2'].label
使用变量时:
y='types1'
x='r_q2'
getattr(User1, y)[x].label
没有问题。