Search code examples
djangodjango-autocomplete-light

How to use django autocomplete with field related to ContentType?


Good day, I am using django-autocomplete-light 3.2.10 for field that is related to ContentType model with ForeignKey relation inside django admin. I need to filter ContentType over its name but it is really a @property. So is there a way to do this?

Update: I needed actually to filter ContentType over models' verbose_name instead of a name.


Solution

  • I've found an answer, it's a little bit ugly but working.

    class TransactionAutocomplete(autocomplete.Select2QuerySetView):
        def get_queryset(self):
            user = self.request.user
            if user.is_authenticated() and user.is_staff:
                if self.q:
                    models = apps.get_models()
                    result_list = []
                    for model in models:
                        if self.q in model._meta.verbose_name:
                            result_list.append(
                                ContentType.objects.get_for_model(model)
                            )
                    return result_list
                else:
                    return ContentType.objects.all()
            else:
                return ContentType.objects.none()