I have a dataset where users may need to edit old records but also choices need to be limited to a set of "active" values. This means the legacy choices need to be added to the queryset of the ModelChoiceField when an instance containing a non-active value is selected.
In my mind the ideal way to do this would be to subclass ModelChoiceField however I cannot seem to find the insertion point of instance data into ModelChoiceField. I am able to make it work by setting the queryset in forms.py but I have a large number of fields this is needed for and was really hoping for a more pythonic/DRY solution.
For example:
models.py
class ActiveChoiceModel(models.Model):
name = models.CharField(max_length=10)
active = models.NullBooleanField(default=False)
class MyModel(models.Model):
fk_activechoicemodel = models.ForeignKey(to='mydb.ActiveChoiceModel')
The queryset for the ModelChoiceField should be:
ActiveChoiceModel.objects.filter(active=True) | ActiveChoiceModel.objects.filter(pk=instance.fk_activechoicemodel.id)
This can be achieved in forms.py as:
Class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance.fk_activechoicemodel:
self.fields['fk_activechoicemodel'].queryset = ActiveChoiceModel.objects.filter(active=True) | ActiveChoiceModel.objects.filter(pk=instance.fk_activechoicemodel.id)
Any thoughts on how to do this clean and DRY for 10's or 100's of 'ActiveChoiceModels'?