'How to remove the choice field based on relationships between instances in the database in Django

I'm new to django and I would like to ask a question about a case that I can't solve if for example I have many categories, in these categories I can have one or more fixed sections eg. section = [a, b, c, d, e] so if I have a module showing these options but I already have section "b" in category "1" how can I remove option "b" from the list so as to have a maximum of one category consisting of 5 non-repeated sections



Solution 1:[1]

class SectionForm(forms.ModelForm):

class Meta:
    model = Section
    fields = ["nome"]


def __init__(self, *args, **kwargs,):
    section_pk = kwargs.pop('section_pk', None)
    super(CategotyForm, self).__init__(*args, **kwargs)
    key = Section.objects.filter(category=section_pk).values_list()
    list_key = list(key)
    exist_section = []
    total_section = ['Section A','Section B','Section C','Section D','Section E']
    for i in range(len(list_key)):
        exist_section.append(list_key[i][1])
    choice = list(set(total_section)- set(exist_section))
    for i in range(len(choice)):
        choice[i] = choice[i].title()
    dict_choice = []
    A = 'Section A'
    B = 'Section B'
    C = 'Section C'
    D = 'Section D'
    E = 'Section E'
    label = ''
    for i in range(len(choice)):
        if choice[i] == 'Section A':
            label = A
        if choice[i] == 'Section B':
            label = B
        if choice[i] == 'Section C':
            label = C
        if choice[i] == 'Section D':
            label = D
        if choice[i] == 'Section E':
            label = E
        dict_choice.append(label)
    new_choice = list(zip(dict_choice, choice))
    self.fields["name"] = forms.ChoiceField(choices=new_choice)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1