I have an administrative website being built using Django.
One of the functionality of website is to allow users to submit quarterly compliance forms. To acheive this, the application design has a QuartersMaster table where site admin can create new quarters (with name, start and end date).
The form to create a new compliance report has a select box where user needs to select the quarter for which report is being created. I have used a ModelChoice field inside the Form class for this Form. The queryset of the field is set dynamically when form is generated (using the .queryset attribute). It queries the QuartersMaster table for all quarters which user has NOT generated a report and shows just those quarters.
This part is working correctly. Now as list of quarters can get very large I had the idea of limiting the query to top x results. For this I used the query slicing on the queryset. But after this the form validation started failing with “Please select a valid choice”.
From debugging I learnt that Django form validation uses the field.queryset.get() method to verify that user given value is part of queryset. The problem is that after slicing a queryset, it is no longer possible to call .get() on queryset.
Is there a workaround I can use to use slicing on ModelChoice querysets and still get validation to work? Maybe by iterating over queryset entries (after getting them from DB) and verifying selected value indeed exists in queryset?