如何优化以下代码

时间:2018-06-02 12:15:54

标签: django

color and size are taken from URL using GET method in django color and size are check box inputs and are recieved as a list in the view.py file

我正在使用颜色和大小属性过滤我的Prouct表

mydict = dict(request.GET)

if 'size' in mydict:
       result1 = Product.objects.filter(attributes__size__in=mydict['size'])

if 'color' in mydict:
       result2 = Product.objects.filter(attributes__color__in=mydict['color'])

result = result1.intersection(result2)

1 个答案:

答案 0 :(得分:0)

此处无需使用intersection。组合过滤器会好得多。此外,request.GET已经是一个词典。

result = Product.objects.all()
if 'size' in request.GET:
    result = result.filter(attributes__size__in=request.GET['size'])
if 'color' in request.GET:
    result = result.filter(attributes__color__in=request.GET['color'])

如果你有很多参数,并且它们都映射到attributes中的元素,你可以动态地执行:

result = Product.objects.all()
for key, value in request.GET:
    result = result.filter(**{'attributes__{}__in'.format(key): value})