how to dynamically populate choices field from another model containing the values to be used - Django

455 Views Asked by At

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

1

There are 1 best solutions below

4
Waldemar Podsiadło On

Use ForeignKey :

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