开发者

Django filter only if the "category" isset!

How can I do this?

I only what to filter if the request is set.

ex. if gender not set, the filter will be: Test.objects.filter(categories=category, brands=brand)

def index(request):
    gender = request.GET.get('gender')
    category = request.GET.get('category')
    brand = request.GET.get('brand')
开发者_如何学JAVA
    Test.objects.filter(genders=gender, categories=category, brands=brand)


If you realize that filter conditions can be passed in as keyword arguments the solution becomes easier to visualize. For e.g. consider the snippet below. This is a verbose way of doing it:

conditions = dict()

for filter_key, form_key in (('genders',  'gender'), ('categories', 'category'), ('brands', 'brand')):
    value = request.GET.get(form_key, None)
    if value:
        conditions[filter_key] = value

Test.objects.filter(**conditions)

Of course another way of doing this would be to use a form rather than pick up the values directly from the GET request.


def index(request):
    gender = request.GET.get('gender', None)
    category = request.GET.get('category')
    brand = request.GET.get('brand')

results = Test.objects.filter(categories=category, brands=brand)
if gender:
    results = results.filter(genders=gender)

If gender is not specified, gender variable will set to None, so following if gender block will not be executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜