带变量的 Django 模型实例
Django Model instance with variable
这是我获得所需值的唯一方法:
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 中有很多文本选择。我没有包括它们,因为它们在这里并不重要。
我使用 getattr()
让它工作。
getattr(User1, 'types1')['r_q2'].label
使用变量时:
y='types1'
x='r_q2'
getattr(User1, y)[x].label
不会有任何问题。
这是我获得所需值的唯一方法:
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 中有很多文本选择。我没有包括它们,因为它们在这里并不重要。
我使用 getattr()
让它工作。
getattr(User1, 'types1')['r_q2'].label
使用变量时:
y='types1'
x='r_q2'
getattr(User1, y)[x].label
不会有任何问题。