django-filter with django autocomplete light

前端 未结 1 1975
情歌与酒
情歌与酒 2021-02-11 07:53

Has anyone succesfully used dal and django-filter together? Below attempt is mine, I tried to use filterset_factory, supplying model class and fields list, then I tried to use f

1条回答
  •  情歌与酒
    2021-02-11 08:26

    I'm not very familiar with DAL, but I contribute to django-filter and have a decent understanding of its internals. A few notes:

    • The filter_class in your filter_overrides should be a filter, not a widget. You can provide additional arguments (such as the widget) through the extra key, as seen here. Any parameter that does not belong to the filter is automatically passed to the underlying form field.
    • Using an override isn't the right approach anyway, as the widget needs a field-specific endpoint to perform autocompletion. Since the endpoint is field-specific, it's not applicable to all ForeignKeys.
    • django-filter uses regular Forms, not ModelForms, so an appropriate Meta inner class would not be constructed. FutureModelForm doesn't seem to provide autocomplete functionality anyway - it seems irrelevant?

    Your factory will have to generate your autocomplete filters manually - something like the following:

    def dal_field(field_name, url):
        return filters.ModelChoiceFilter(
            name=field_name,
            widget=autocomplete.ModelSelect2(url=url),
        )
    
    def dal_filterset_factory(model, fields, dal_fields):
        attrs = {field: dal_field(field, url) for field, url in dal_fields.items()}
        attrs['Meta'] = type(str('Meta'), (object,), {'model': model,'fields': fields})
    
        filterset = type(str('%sFilterSet' % model._meta.object_name),
                         (FilterSet,), attrs)
        return filterset
    
    # Usage:
    
    # mapping of {field names: autocomplete endpoints}.
    dal_fields = {'birth_country': 'country-autocomplete'}
    fields = ['list', 'or', 'dict', 'of', 'other', 'fields']
    SomeModelFilterSet = dal_filterset_factory(SomeModel, fields, dal_fields)
    

    The fields in attrs use the declarative API. More info in the docs.

    0 讨论(0)
提交回复
热议问题