farhan0581 / django-admin-autocomplete-filter

A simple Django app to render list filters in django admin using autocomplete widget.
GNU General Public License v3.0
351 stars 76 forks source link

'DeferredAttribute' object has no attribute 'get_queryset' (choices and integers) #93

Closed lguariento closed 7 months ago

lguariento commented 8 months ago

Hello,

I noticed that I get a 'DeferredAttribute' object has no attribute 'get_queryset' when I add an integerfield or a Choices field to a filter class. E.g.:

models:

class MyModel:
    CHOICES = [
        ("1", "1"),
        ("2", "2"),
    ]

    my_choice = models.CharField(choices=CHOICES, max_length=30)

admin:

class ChoicesFilter(AutocompleteFilter):
    title = 'Choices'
    field_name = 'my_choice'

I think I've identified the offending lines. They are in /admin_auto_filters/filters.py:

def get_queryset_for_field(model, name):
        try:
            field_desc = getattr(model, name)
        except AttributeError:
            field_desc = model._meta.get_field(name)
        if isinstance(field_desc, ManyToManyDescriptor):
            related_model = field_desc.rel.related_model if field_desc.reverse else field_desc.rel.model
        elif isinstance(field_desc, ReverseManyToOneDescriptor):
            related_model = field_desc.rel.related_model  # look at field_desc.related_manager_cls()?
        elif isinstance(field_desc, ForeignObjectRel):
            # includes ManyToOneRel, ManyToManyRel
            # also includes OneToOneRel - not sure how this would be used
            related_model = field_desc.related_model
        else:
            # primarily for ForeignKey/ForeignKeyDeferredAttribute
            # also includes ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ReverseOneToOneDescriptor
            return field_desc.get_queryset()
        return related_model.objects.get_queryset()

Would adding an extra elif such as elif isinstance(field_desc, Choices) do? And same for integers? That would be great.

sevdog commented 8 months ago

I belive that this use case is not covered at all. This filter was supposed to be used for related models not for choices. The field_name should be a relation field not a normal one.