How can I optimize the following code

后端 未结 1 1755
我寻月下人不归
我寻月下人不归 2021-01-26 14:01

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

I am filtering my Prouct

相关标签:
1条回答
  • 2021-01-26 14:41

    There is no need to use intersection here. A combined filter would be much better. Also, request.GET is already a dict.

    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'])
    

    If you've got lots of parameters, and they all map to elements in attributes, you could do it dynamically:

    result = Product.objects.all()
    for key, value in request.GET:
        result = result.filter(**{'attributes__{}__in'.format(key): value})
    
    0 讨论(0)
提交回复
热议问题