Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Django filter args as arguments to other function

Tags:

python

django

I want to make a class function that returns the result of a filter, but I want to be able to use it as if the function was a django filter too:

This is what I've tried:

def section_set_with_compound(self, *args, **kwargs):
    print args
    print kwargs
    return self.section_set.filter(Q(args) |Q(course__is_compound=True))

But im getting an error as if args and kwags are empty:

I want to be able to do:

myobject.section_set_with_compound(param1=1,param2__param3__=x,param4__icontains="ha..")

How can I accomplish this?

like image 994
Pablo Estrada Avatar asked Nov 15 '25 09:11

Pablo Estrada


1 Answers

You need to use the asterisk and double asterisk (*) in the call to Q as well:

def section_set_with_compound(self, *args, **kwargs):
    return self.section_set.filter(Q(*args, **kwargs) | Q(course__is_compound=True))

The args is a tuple with the unnamed parameters, kwargs is a dictionary with the named parameters. But in case you want to pass these again as unnamed and named parameters, you need to do a call with the asterisk as well.

Note that here you have constructed a logical OR, this means that the elements should or satisfy the filter with the arguments you work with, or the course__is_compound is True (or both at the same time).

In case you want a logical AND, you can use:

def section_set_with_compound(self, *args, **kwargs):
    return self.section_set.filter(*args, course__is_compound=True, **kwargs)

Now Django will filter rows such that all the conditions you enter hold, and the course__is_compound is set to True. This is semantically different compared to the first code fragment.

like image 63
Willem Van Onsem Avatar answered Nov 18 '25 00:11

Willem Van Onsem