[英]how to dynamically populate choices field from another model containing the values to be used - Django
I have a model that has some choices that the admin chooses while entering some data in the admin pannel.我有一个 model 有一些管理员在管理面板中输入一些数据时选择的选项。 I am using the general way of making a choice field as below我正在使用如下一般方式来制作选择字段
CATEGORY= (
('arbitration', 'arbitration'),
('binding precedent', 'binding precedent'),
('contempt', 'contempt'),
('execution of decree', 'executuon of decree'),
('limitations', 'limitations'),
('negative equality', 'negative equality'),
('od/ss/rd', 'Obitor Dicta / Sub Silenso-Ratio/ Decidendi'),
('review', 'review'),
('special relief', 'special relief'),
)
)
class Civil(models.Model):
law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required")
Here the choices are hard coded.这里的选择是硬编码的。 Now I want the admin to have control over what choices he can have inside CATEGORY .现在我希望管理员能够控制他在CATEGORY中可以有哪些选择。 So what I thought would work is to create another model where he can enter the the values for CATEGORY and that would in return create some dynamic choices for the field law_category= models.CharField(max_length=60, choices=CATEGORY,null=True, help_text="required")
所以我认为可行的是创建另一个 model ,他可以在其中输入CATEGORY的值,这将反过来为字段law_category= models.CharField(max_length=60, choices=CATEGORY,null=True, help_text="required")
The way I approached the problem was as below我解决问题的方法如下
class CivilChoices(models.Model):
key=models.CharField()
value = models.CharField()
Here I thought of entering the key and values.在这里,我想到了输入键和值。 But now I do not know how to get these values inside the Civil model for CATEGORY to use, or even if it is the right way to do it.但是现在我不知道如何在Civil model 中获取这些值以供CATEGORY使用,或者即使它是正确的方法。
Please suggest me a way to create dynamic choices for the law_category field that get its choices from another model请建议我一种为law_category字段创建动态选择的方法,该字段从另一个 model 获取其选择
Use ForeignKey:使用外键:
class Civil(models.Model):
law_category = models.ForeignKey(CivilChoices, on_delete=models.SET_NULL, null=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.