Dynamically pass arguments to objects.filter

I am pretty new to Django and I am trying to get a query set from a filter function. This filter function is supposed to be able to take 1 to 5 arguments and I am not sure how to handle that.

I have not found anything here that might help me, so if you do know of some other question that might help please let me know.

views.py:

@api_view(('Get',))

def update(request, REQUEST):

    if request.method == "Get":
        requestlist = REQUEST.split('&')
        for keys in requestlist:
            if 'module' in keys:
                module = keys[8:]
            if 'value' in keys:
                value = keys[6:]
            if 'user' in keys:
                user= keys[5:]
            if 'time1' in keys:
                time1 = keys[6:]
            if 'time2' in keys:
                time2 = keys[6:]
        item = Post.objects.filter(name=Name, user=USER, ...)

The full request string will look like name=NAME&value=VALUE&user=USER&time1=FIRSTTIME&time2=SECONDTIME but it could also be any combination of the individual variables like name&time1.

Now I want to be able to do that with one filter method instead of creating like 2^5 for each different szenario.

Answer

The full request string will look like name=NAME&value=VALUE&user=USER&time1=FIRSTTIME&time2=SECONDTIME.

This is a query string [wiki], and Django automatically parses this to a dictionary-like QueryDict, you thus should not specify this yourself. You can work with:

if request.method == 'GET':
    Post.objects.filter(**request.GET.dict())

I would however advise to only allow specific keys, and thus not all keys, since then the database is less secure: one can use the filtering mechanism to retrieve data.

It thus might be better to work with:

datas = {}
accept_keys = {'module', 'value', 'user', 'time1', 'time2'}

for key, value in request.GET.dict().items():
    if key in accept_keys:
        datas[key] = value

if request.method == 'GET':
    Post.objects.filter(**datas)

In that case the item after the path is the query string, and the separator between the path and the query string is a question mark (?).

The path thus looks like:

urlpatterns = [
    # …,
    path('some/path/', views.update, name='update'),
    # …
]

and you thus query the path with some.host.com/some/path?name=NAME&value=VALUE&user=USER&time1=FIRSTTIME&time2=SECONDTIME.