Home > Enterprise >  How to stack filters if parameters exist or not?
How to stack filters if parameters exist or not?

Time:11-20

If I have something such as this:

    tasks = Task.objects.filter( 
        Q(datetime__contains=date)
        & Q(user=uid) if uid!=0 else
        & Q(member=mid) if mid!=0 else
        & Q(job=jid) if jid!=0 else
    )

It will stack/mix the filters dependent on what function parameters are passed, but obviously that doesn't work, what is the best way to continue?

CodePudding user response:

You can chain calls to filter within if statements to "stack" conditional filters

tasks = Task.objects.filter( 
    datetime__contains=date
)
if uid != 0:
    tasks = tasks.filter(user=uid)
if mid != 0:
    tasks = tasks.filter(member=mid)
if jid != 0:
    tasks = tasks.filter(job=jid)

CodePudding user response:

A simple way might be dictionary unpacking:

data = {'user': uid, 'member': mid, 'job': jid}

tasks = Task.objects.filter(
    **{ k: v for k, v in data.items() if v != 0 },
    datetime__contains=date
)
  • Related