简体   繁体   中英

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. 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 . 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")

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.

Please suggest me a way to create dynamic choices for the law_category field that get its choices from another model

Use ForeignKey:

class Civil(models.Model):
    law_category = models.ForeignKey(CivilChoices, on_delete=models.SET_NULL, null=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM