Django Dynamic Filter

So, I want to create a django filters.FilterSet from a django filter module , but I want to add its attributes dynamically. For example, if I would like to add SubNamedynamically:

class UsersInfoFilter(filters.FilterSet):
    Name=NumberFilter(lookup_type='gte')
    def __new__(self):
        self.SubName=NumberFilter(lookup_type='gte')
        self.Meta.fields.append('SubName')
    class Meta:
        model = UsersInfo
        fields = ['UserID', 'LanguageID', 'Name']

The problem is that the FilterSet is a metaclass that runs immediately after the class has been computed, so up to this point there is nothing that elements could be dynamically added.

I tried to put the function as a parameter around filters.FilterSet class UsersInfo(AddObjects(filters.FilterSet)), which returns exactly what passes, but I cannot reference at UsersInfoFilterthat point, since it is not finished yet.

I also tried to make it UsersInfoFiltermy own base class and then create class RealUsersInfoFilter(UsersInfoFilter, filters.FilterSet)as my actual filter, but then FilterSet just gives warnings about missing attributes named as fields.

There seems to be no constructor function for classes in python. I suppose I need to do some magic with metaclasses, but I have tried every combination that I can think of and am at the end.

+4
source share
1 answer

You cannot change a subclass Metafrom a method __init__... there are 2 options to approach your problem ...

- "" :

class UsersInfoFilter(filters.FilterSet):
    class Meta:
        model = UsersInfo

.

-, :

class UsersInfoFilter(filters.FilterSet):
    name = NumberFilter(lookup_type='gte')

    def __init__(self):
        super(UsersInfoFilter, self).__init__()

        base_filters['subname'] = NumberFilter(name='subname', lookup_type='gte')

    class Meta:
        model = UsersInfo
        fields = ['user_id', 'language_id', 'name']

( , , , , "" , - )

p.s. CamelCase ? pep-8.

0

Source: https://habr.com/ru/post/1629285/


All Articles