Using the Django Grappelli admin tools, I can configure a ForeignKey (many-to-one) field to display as an autocomplete widget, rather than a drop down field, as follows:
class MyModel(models.Model):
related = models.ForeignKey(RelatedModel, related_name='my_models')
class MyModelAdmin(admin.ModelAdmin):
raw_id_fields = ('related',)
autocomplete_lookup_fields = {
'fk': ['related'],
}
However, what I'd like to do is define autocomplete widget lookups in the other (one-to-many) direction (i.e. in the admin for the RelatedModel so I can lookup one or more MyModel objects). Right now, I'm just using a ModelMultipleChoiceField:
class RelatedModelForm(forms.ModelForm):
class Meta:
model = RelatedModel
fields = ('my_models',)
my_models = forms.ModelMultipleChoiceField(queryset=MyModel.objects.all())
def __init__(self, *args, **kwargs):
super(SaleAdminForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['foods'].initial = self.instance.foods.all()
def save(self, *args, **kwargs):
instance = super(RelatedModelForm, self).save(commit=False)
self.fields['my_models'].initial.update(related=None)
self.cleaned_data['my_models'].update(related=instance)
return instance
class RelatedModelAdmin(admin.ModelAdmin):
model = RelatedModel
form = RelatedModelForm
However, there are just too many MyModel instances to work well with that type of widget. It would be ideal to just have one or more autocomplete lookup widgets for MyModel objects, in place of the ModelMultipleChoiceField.
Grappelli has an easy way to make autocomplete lookups for FK relations and for m2m relations, but is there a way for one-to-many relations? It seems like autocompletes for those would be just as useful as for the other two types of relations, so I would have guessed that Grappelli would provide an easy way there also, but I'm not finding it...