如何解决具有变量的Django模型实例
这是我获得所需价值的唯一方法:
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。我没有包括它们,因为它们在这里并不重要。
解决方法
我通过使用getattr()
使它正常工作。
getattr(User1,'types1')['r_q2'].label
使用变量时:
y='types1'
x='r_q2'
getattr(User1,y)[x].label
没有问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。