如何在django中按列表过滤

时间:2021-10-19 01:34:36

I am trying to filter a queryset by a list I am getting unicode data into format of 1,4,5,6 by

我试图通过列表过滤查询集我将unicode数据转换为1,4,5,6的格式

category = request.GET.getlist(category')
print type(category)



data = Leads.objects.filter(item_required__id= category ) 

then i am getting a error

然后我收到一个错误

invalid literal for int() with base 10: '1,4'

So how can i fix this.

那么我该如何解决这个问题呢。

Traceback:
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/home/cp/Documents/myshopup/markatix/customapi/vendors.py" in CustomerRequirements
  365.      cust_leads = CustomerLeads.objects.filter(item_required__id__in= category ).values('customer_name','budget','event','posting_date','quantity','other','fb_id','image','title').order_by('-posting_date')
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
  679.         return self._filter_or_exclude(False, *args, **kwargs)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  697.             clone.query.add_q(Q(*args, **kwargs))
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1310.         clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1338.                     allow_joins=allow_joins, split_subq=split_subq,
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1209.             condition = self.build_lookup(lookups, col, value)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_lookup
  1102.                 return final_lookup(lhs, rhs)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__
  105.         self.rhs = self.get_prep_lookup()
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/lookups.py" in get_prep_lookup
  143.         return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
  729.             return [self.get_prep_value(v) for v in value]
File "/home/cp/Documents/envMyShopUp/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  985.         return int(value)

Exception Type: ValueError at /customapi/vendor/customer-requirements/
Exception Value: invalid literal for int() with base 10: '1,4'

Thanks in advance.

提前致谢。

2 个解决方案

#1


0  

I done some steps wrong.finally i got and found solution.

我做错了一些步骤。最后我得到了解决方案。

    category = request.GET.get('category')
l1=[]
    category_list =category.split(',')
    for i in category_list:
        a =int(i)
        l1.append(a)

cust_leads = CustomerLeads.objects.filter(item_required__id__in= l1 )

#2


0  

You can also use the QueryDict.getlist to resolve query parameter lists for your request:

您还可以使用QueryDict.getlist来解析请求的查询参数列表:

from django.http.request import QueryDict

query = QueryDict('category=1&category=2')
categories = query.getlist('category')  # -> ['1', '2']
leads = Leads.objects.filter(item_required__id__in=categories)

This way user can supply you a list of categories by adding them one-by-one into the query. This solution might be good enough for you.

这样,用户可以通过逐个添加到查询中来为您提供类别列表。这个解决方案对您来说可能已经足够了。

However, your user (or you) might want to supply free style lists, and they might be multiple in your queries. In that case you would have to get all lists, which can be lists of primary keys, and map them to a flat list which can be used in a Django filter...

但是,您的用户(或您)可能希望提供免费样式列表,并且它们在您的查询中可能是多个。在这种情况下,您必须获取所有列表,可以是主键列表,并将它们映射到可以在Django过滤器中使用的平面列表...

from itertools import chain
from django.http.request import QueryDict

query = QueryDict('categories=1,2,3&categories=4,5')
categories_strings = query.getlist('categories')  # -> ['1,2,3', '4,5']
categories = list(chain.from_iterable(
    map(lambda categories: categories.split(','), categories_strings))
)  # -> ['1', '2', '3', '4', '5']
leads = Leads.objects.filter(item_required__id__in=categories)

Luckily for us, you could easily write this into a neat little function:

幸运的是,你可以轻松地将它写成一个简洁的小功能:

# Your myapp/utils.py module
from itertools import chain

# Python 3.5+ type type annotated function, you can use
# this without the type annotations in Python 2.7 as well
def get_query_list(querydict: QueryDict, key: str) -> list:
    return list(chain.from_iterable(
        map(lambda query: query.split(','), querydict.getlist(key)))
    )

And this is how it works:

这就是它的工作原理:

from django.http.request import QueryDict
from myapp.utils import get_query_list

q = QueryDict('a=1&a=2&a=3,4')
get_query_list(q, 'a')  # -> ['1', '2', '3', '4']

You can use it from your view:

您可以在视图中使用它:

# Your myapp/views.py module
from myapp.utils import get_query_list

def my_view(request):
    categories = get_query_list(request.GET, 'categories')  # or 'category'
    # ...

This is the more verbose way instead of using a singular query parameter in place of a list and supports multiple different formats.

这是更冗长的方式,而不是使用单个查询参数代替列表并支持多种不同的格式。

Add type assortions as necessary:

根据需要添加类型分类:

def my_view(request):
    # A nice and neat one-liner
    categories = get_query_list(request.GET, 'categories')  # or 'category'
    for item in categories:
        try:
            assert int(item)
        except ValueError:
            raise ValidationError('{} is not of correct type {}'.format(item, int))
    # Everything should be parsed and validated
    leads = Leads.objects.filter(item_required__id__in=categories)

This approach is often needed with Django when implementing search or generic filters.

Django在实现搜索或通用过滤器时经常需要这种方法。

#1


0  

I done some steps wrong.finally i got and found solution.

我做错了一些步骤。最后我得到了解决方案。

    category = request.GET.get('category')
l1=[]
    category_list =category.split(',')
    for i in category_list:
        a =int(i)
        l1.append(a)

cust_leads = CustomerLeads.objects.filter(item_required__id__in= l1 )

#2


0  

You can also use the QueryDict.getlist to resolve query parameter lists for your request:

您还可以使用QueryDict.getlist来解析请求的查询参数列表:

from django.http.request import QueryDict

query = QueryDict('category=1&category=2')
categories = query.getlist('category')  # -> ['1', '2']
leads = Leads.objects.filter(item_required__id__in=categories)

This way user can supply you a list of categories by adding them one-by-one into the query. This solution might be good enough for you.

这样,用户可以通过逐个添加到查询中来为您提供类别列表。这个解决方案对您来说可能已经足够了。

However, your user (or you) might want to supply free style lists, and they might be multiple in your queries. In that case you would have to get all lists, which can be lists of primary keys, and map them to a flat list which can be used in a Django filter...

但是,您的用户(或您)可能希望提供免费样式列表,并且它们在您的查询中可能是多个。在这种情况下,您必须获取所有列表,可以是主键列表,并将它们映射到可以在Django过滤器中使用的平面列表...

from itertools import chain
from django.http.request import QueryDict

query = QueryDict('categories=1,2,3&categories=4,5')
categories_strings = query.getlist('categories')  # -> ['1,2,3', '4,5']
categories = list(chain.from_iterable(
    map(lambda categories: categories.split(','), categories_strings))
)  # -> ['1', '2', '3', '4', '5']
leads = Leads.objects.filter(item_required__id__in=categories)

Luckily for us, you could easily write this into a neat little function:

幸运的是,你可以轻松地将它写成一个简洁的小功能:

# Your myapp/utils.py module
from itertools import chain

# Python 3.5+ type type annotated function, you can use
# this without the type annotations in Python 2.7 as well
def get_query_list(querydict: QueryDict, key: str) -> list:
    return list(chain.from_iterable(
        map(lambda query: query.split(','), querydict.getlist(key)))
    )

And this is how it works:

这就是它的工作原理:

from django.http.request import QueryDict
from myapp.utils import get_query_list

q = QueryDict('a=1&a=2&a=3,4')
get_query_list(q, 'a')  # -> ['1', '2', '3', '4']

You can use it from your view:

您可以在视图中使用它:

# Your myapp/views.py module
from myapp.utils import get_query_list

def my_view(request):
    categories = get_query_list(request.GET, 'categories')  # or 'category'
    # ...

This is the more verbose way instead of using a singular query parameter in place of a list and supports multiple different formats.

这是更冗长的方式,而不是使用单个查询参数代替列表并支持多种不同的格式。

Add type assortions as necessary:

根据需要添加类型分类:

def my_view(request):
    # A nice and neat one-liner
    categories = get_query_list(request.GET, 'categories')  # or 'category'
    for item in categories:
        try:
            assert int(item)
        except ValueError:
            raise ValidationError('{} is not of correct type {}'.format(item, int))
    # Everything should be parsed and validated
    leads = Leads.objects.filter(item_required__id__in=categories)

This approach is often needed with Django when implementing search or generic filters.

Django在实现搜索或通用过滤器时经常需要这种方法。