I would like to limit the choices for a ForeignKey in the admin UI using limit_choices_to; however, I would like to achieve this without changing the model, since the model is brought in from a library, that I don't have control over. What is the way of dynamically achieving this? Or could I use a field on the admin model to be able to achieve this?
Thanks, --Eytan
Django provides an admin hook to modify a foreign keys queryset: formfield_for_foreignkey
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With