-
-
Notifications
You must be signed in to change notification settings - Fork 351
Open
Description
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.
- setting limit_choices_to in models.py in the chainedforeignkey field
- 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 :)
Metadata
Metadata
Assignees
Labels
No labels