Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

need to get data for choice fields in Django form a loop?

The choice field required in django is in the following format

new_choices = (
    (1, 'Data 1'),
    (2, 'Data 2'),
    (3, 'Data 3'),
    (4, 'Data 4'),
    (5, 'Data 5'),
    (6, 'Data 6'),
    (7, 'Data 7'),
     )

I am trying to get the data from db but the data is not getting properly

        CHOICES =  heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
        test =([('(' + str(p.head) + '-' + p.detail + ')') for p in CHOICES])
        len_of_test = len(test)
        
        new_choices =[]
        for n in range(len_of_test):
         new_choices = '(' + str(n) + "," + test[n] + ')'
 

The output I am getting from the above code is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_choices = ['(0,(Data 0))','(1,(Data 1))','(2,(Data 2))',...]

need to get the output as below

 new_choices = (
    (1, 'Data 1'),
    (2, 'Data 2'),
    (3, 'Data 3'),
    (4, 'Data 4'),
    (5, 'Data 5'),
    (6, 'Data 6'),
    (7, 'Data 7'),
     )

>Solution :

You can construct a list of 2-tuples with:

CHOICES =  heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
new_choices = [
    (i, f'{p.head}-{p.detail}')
    for i, p in enumerate(CHOICES, 1)
]

But populating data from a QuerySet often is not necessary. Usually a ModelChoiceField is used to pick an element for a ForeignKey.

That being said, you probably are looking for a ModelChoiceField [Django-doc] which is a ChoiceField populated by a queryset.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading