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

Time:12-19

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

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'),
     )

CodePudding user response:

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.

CodePudding user response:

As Willem Van Onsem notes in a comment, you should probably use database IDs instead of 0,1,... as the keys in the list of choices.

I would use an approach like the following:

qs = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1)
new_choices = []
for p in qs:
    label = '('   str(p.head)   '-'   p.detail   ')'
    new_choices.append((p.id, label))
  • Related