2👍
This can’t be done with limit_choices_to.
But you can use two different approaches that work OK:
1) For ForeignKeys
you can use formfield_for_foreignkey
to override the queryset in your ModelAdmin like this:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.user.is_superuser:
return super(UserOwnerProtectorModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == "task":
# This next line only shows owned objects
# but you can write your own query!
kwargs["queryset"] = db_field.related_model.objects.filter(user=request.user)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
2) And as a second choice here is an example that overrides the field queryset which can help you on the OneToOne field:
Django ForeignKey limit_choices_to a different ForeignKey id
Good luck!
0👍
Limit_choices_to is a Q object.
In docs you have an example of making similar restriction on ForeignKey: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to
More about queries is here: https://docs.djangoproject.com/en/dev/topics/db/queries/
👤kszl
- [Answered ]-How do I optimize the following Django model queries?
- [Answered ]-Authomatic: REQUEST is deprecated / The returned state doesn't match with the stored state
Source:stackexchange.com