jazzband / django-smart-selects

chained and grouped selects for django forms
https://django-smart-selects.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
1.1k stars 348 forks source link

Cannot set queryset for Chainedforeignkey #351

Open R3guluss opened 11 months ago

R3guluss commented 11 months ago

hi, I am working with the chainedforeignkey field for my website, however I am unable to define the queryset for the chainedforeignkey to query.

Models.py

class Class_Catalogue(models.Model):
    class_ID = models.CharField(max_length=100, primary_key=True)
    class_start_date = models.DateField()
    class_age_group = models.CharField(max_length=5)
    active = models.BooleanField(default=True)

class Enrollment(models.Model):
    enrollment_ID = models.AutoField(primary_key=True)
    class_ID = ChainedForeignKey(Class_Catalogue, chained_field='class_date',chained_model_field='class_start_date')
    class_date = models.DateField()
    customer = models.ForeignKey(Customer, to_field='phone_number', on_delete=models.PROTECT, related_name='enrollments')

so the goal here is to let the customer choose the class date first, and then they can select the class_ID according to the class date. However, they should be able to choose only the classes which are active (active=True) and matches their age group.

So originally I did this by setting the queryset in forms.py

    def __init__(self, *args, **kwargs):
        super(Enrollment_form, self).__init__(*args, **kwargs)
        customer = Customer.objects.get(phone_number=self.initial['customer'])
        if customer.age_group not in ['1','2']:
            age_group = 'adult'
        else:
            age_group = customer.age_group
        self.fields['class_ID'].queryset = Class_Catalogue.objects.filter(active=True, class_age_group=age_group) | Class_Catalogue.objects.filter(active=True, class_age_group='all')

After using django-smart-selects, I have tried 2 methods.

  1. setting limit_choices_to in models.py in the chainedforeignkey field
  2. setting the formfield in forms.py
    class_ID = ChainedModelChoiceField(
        to_app_name='backend',
        to_model_name='Class_Catalogue',
        chained_field='class_date',
        chained_model_field='class_start_date',
        foreign_key_app_name='backend',
        foreign_key_model_name='Enrollment',
        foreign_key_field_name='class_date',
        show_all=False,
        auto_choose=False,
        queryset = Class_Catalogue.objects.filter(active=True) #for testing only
    )

But none of the method works and now I am stuck. Thanks :)