本文整理汇总了Python中django.db.models.Q.OR属性的典型用法代码示例。如果您正苦于以下问题:Python Q.OR属性的具体用法?Python Q.OR怎么用?Python Q.OR使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类django.db.models.Q
的用法示例。
在下文中一共展示了Q.OR属性的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: searchThreat
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def searchThreat(keyword_list):
logger.info("search: %s", keyword_list)
events = Event.objects.all()
q_info = Q()
for keyword_or in keyword_list:
q_info_and = Q()
for keyword_and in keyword_or:
q_info_and.add(Q(info__icontains=keyword_and), Q.AND)
q_info.add(q_info_and, Q.OR)
q_attr = Q()
for keyword_or in keyword_list:
q_attr_and = Q()
for keyword_and in keyword_or:
q_attr_and.add(Q(value__icontains=keyword_and), Q.AND)
q_attr.add(q_attr_and, Q.OR)
event_list = Attribute.objects.filter(q_attr).values_list('event')
return events.filter(q_info| Q(id__in=event_list))
示例2: get_queryset
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def get_queryset(self):
qs = self.queryset
if self.q:
# Split the terms into words and build a Q object
search_terms = self.q.split(' ')
query = Q()
for term in search_terms:
fields_query = Q()
for field in self.filter_fields:
fields_query.add(Q(**{field: term}), Q.OR)
query.add(fields_query, Q.AND)
qs = qs.filter(query)
return qs
示例3: get_editable_permissions
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def get_editable_permissions(self):
"""
Return a queryset of Permission objects that can be assigned
The view has an attribute called `editable_permissions` but that
attribute only lists app names and permission codenames. We need to
turn that tuple of tuples into a queryset of permissions.
"""
# Dynamic generation of OR queries is based on code found at
# https://bradmontgomery.net/blog/adding-q-objects-in-django/
permission_filter = Q()
for permission in self.editable_permissions:
permission_filter.add(
Q(content_type__app_label=permission[0],
codename=permission[1]), Q.OR)
return Permission.objects.filter(
permission_filter)
示例4: shipping_options
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def shipping_options(request, country=None):
"""
Get the shipping options for a given country
"""
try:
kwargs = get_shipping_cost_kwargs(request, country=country)
except (utils.InvalidShippingCountry, utils.InvalidShippingDestination) as e:
return Response(data={'message': e.message}, status=status.HTTP_400_BAD_REQUEST)
country_code = kwargs['country_code']
settings = kwargs['settings']
bid = kwargs['basket_id']
destination = kwargs['destination']
processors = ShippingRateProcessor.objects.filter(countries__in=[country_code])
if processors:
if not destination:
return Response(
data={
"message": "Destination address is required for rates to {}.".format(country_code)
},
status=status.HTTP_400_BAD_REQUEST
)
for processor in processors:
processor.get_rates(settings=settings, basket_id=bid, destination=destination)
q = Q(countries__in=[country_code]) | Q(basket_id=bid, destination=None)
if destination:
q.add(Q(destination=destination, basket_id=''), Q.OR)
q.add(Q(destination=destination, basket_id=bid), Q.OR)
qrs = models.ShippingRate.objects.filter(q)
serializer = serializers.ShippingRateSerializer(qrs, many=True)
return Response(
data=serializer.data,
status=status.HTTP_200_OK
)
示例5: queryset
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def queryset(self):
queryset = Q()
for tag_type in self._tags:
queryset.add(Q(tag_loading=tag_type[0]) & Q(tag_type=tag_type[1]), Q.OR)
return queryset
示例6: makeKeywordList
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def makeKeywordList(keyword):
# , is OR. ' ' is AND
keyword_list = []
for klist in re.sub(r' *,+ *', ',', keyword).split(','):
keyword_list.append(klist.split())
return keyword_list
示例7: searchNews
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def searchNews(keyword_list):
logger.info("search: %s", keyword_list)
newss = News.objects.all()
q_info = Q()
for keyword_or in keyword_list:
q_info_and = Q()
for keyword_and in keyword_or:
q_info_and.add(Q(content__icontains=keyword_and)|Q(title__icontains=keyword_and), Q.AND)
q_info.add(q_info_and, Q.OR)
return newss.filter(q_info)
示例8: get
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def get(self, request) :
strval = request.GET.get("search", False)
if strval :
# Simple title-only search
# objects = Post.objects.filter(title__contains=strval).select_related().order_by('-updated_at')[:10]
# Multi-field search
query = Q(title__contains=strval)
query.add(Q(text__contains=strval), Q.OR)
objects = Post.objects.filter(query).select_related().order_by('-updated_at')[:10]
else :
# try both versions with > 4 posts and watch the queries that happen
objects = Post.objects.all().order_by('-updated_at')[:10]
# objects = Post.objects.select_related().all().order_by('-updated_at')[:10]
# Augment the post_list
for obj in objects:
obj.natural_updated = naturaltime(obj.updated_at)
ctx = {'post_list' : objects, 'search': strval}
retval = render(request, self.template_name, ctx)
dump_queries()
return retval;
# References
# https://docs.djangoproject.com/en/3.0/topics/db/queries/#one-to-many-relationships
# Note that the select_related() QuerySet method recursively prepopulates the
# cache of all one-to-many relationships ahead of time.
# sql “LIKE” equivalent in django query
# https://stackoverflow.com/questions/18140838/sql-like-equivalent-in-django-query
# How do I do an OR filter in a Django query?
# https://stackoverflow.com/questions/739776/how-do-i-do-an-or-filter-in-a-django-query
# https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running
示例9: filter_Q
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def filter_Q(name, operator, value, valid_tags):
logger.info('filter_Q %s %s %s', name, operator, value)
# do a dynamic Q filter, for example:
# kwargs = {
# '{0}__{1}'.format('name', 'startswith'): 'A',
# '{0}__{1}'.format('name', 'endswith'): 'Z'
# }
# Q(**kwargs)
#
# topic is the only direct field
# for all others we check both in kv_tags and bacnet_fields
# -> note: bacnet_fields are not availabe in the Crate entity yet
# for present and absent we also check in m_tags (using the operator isnull)
#
if 'topic' == name:
return Q(**{'topic__{0}'.format(operator): value})
else:
condition = Q()
if name in valid_tags:
condition.add(Q(**{'kv_tags__{0}__{1}'.format(name, operator): value}), Q.OR)
else:
# for NotEqual, NotContain, Absent we do not need to check the kv_tags since the
# value does not exist at all
# for Present this will just check the m_tags array
# for Equal and Contain we already check in apply_filter_to_queryset
pass
if operator == 'isnull' and not value:
# note this is only for operator isnull
# note: only contains which is equivalent to isnull=False
condition.add(Q(**{'m_tags__contains': [name]}), Q.OR)
return condition
示例10: apply_filter_to_queryset
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def apply_filter_to_queryset(qs, filter_field, filter_type, filter_value, valid_tags):
logger.info('apply_filter_to_queryset: %s %s %s', filter_field, filter_type, filter_value)
if not filter_field or filter_field == 'undefined' or filter_field == 'Topic':
name = 'topic'
else:
name = filter_field
if filter_type:
if filter_type == 'present':
qs = qs.filter(filter_Q(name, 'isnull', False, valid_tags))
elif filter_type == 'absent':
qs = qs.exclude(filter_Q(name, 'isnull', False, valid_tags))
elif filter_value:
# all of those test either topic OR a kv_tags
# so fail if trying to match a kv_tag
prefix = 'i'
if not name == 'topic' and name not in valid_tags and (filter_type == 'c' or filter_type == 'eq'):
logger.warning('topic filter found an unused tag: %s', name)
return qs.none()
if filter_type == 'c':
qs = qs.filter(filter_Q(name, prefix + 'contains', filter_value, valid_tags))
elif filter_type == 'nc':
qs = qs.exclude(filter_Q(name, prefix + 'contains', filter_value, valid_tags))
elif filter_type == 'eq':
qs = qs.filter(filter_Q(name, prefix + 'exact', filter_value, valid_tags))
elif filter_type == 'neq':
qs = qs.exclude(filter_Q(name, prefix + 'exact', filter_value, valid_tags))
elif filter_type == 'matches':
qs = qs.filter(filter_Q(name, prefix + 'regex', filter_value, valid_tags))
elif filter_type == 'gt':
qs = qs.filter(filter_Q(name, 'gt', filter_value, valid_tags))
elif filter_type == 'gte':
qs = qs.filter(filter_Q(name, 'gte', filter_value, valid_tags))
elif filter_type == 'lt':
qs = qs.filter(filter_Q(name, 'lt', filter_value, valid_tags))
elif filter_type == 'lte':
qs = qs.filter(filter_Q(name, 'lte', filter_value, valid_tags))
return qs
示例11: get_product_list_objects
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def get_product_list_objects(self):
q_filter = Q()
for product_id in self.get_string_product_list_as_list():
q_filter.add(Q(product_id=product_id, vendor_id=self.vendor_id), Q.OR)
return Product.objects.filter(q_filter).prefetch_related("vendor", "product_group")
示例12: group_and_or
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def group_and_or(request, search_group_id):
search_group = get_object_or_404(SearchGroup, pk=search_group_id)
saved_search = search_group.saved_search
if is_global_admin(request.user) or request.user == saved_search.created_by:
if search_group.and_or == 'AND':
search_group.and_or = 'OR'
else:
search_group.and_or = 'AND'
search_group.save()
return redirect(build_search, saved_search.id)
# Delete group
示例13: get_shipping_cost
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def get_shipping_cost(settings, country_code=None, name=None, basket_id=None, destination=None):
"""Return the shipping cost for a given country code and shipping option (shipping rate name)
"""
if not country_code and destination:
country_code = destination.country.pk
shipping_rate = None
invalid_country = False
if settings.default_shipping_enabled:
shipping_rate = {
"rate": settings.default_shipping_rate,
"description": "Standard shipping to rest of world",
"carrier": settings.default_shipping_carrier
}
elif not country_code:
invalid_country = True
if country_code:
qrs = models.ShippingRate.objects.filter(countries__in=[country_code], name=name)
count = qrs.count()
if count == 1:
shipping_rate_qrs = qrs[0]
shipping_rate = {
"rate": shipping_rate_qrs.rate,
"description": shipping_rate_qrs.description,
"carrier": shipping_rate_qrs.carrier}
if basket_id or destination:
q = Q()
if destination and basket_id:
q.add(Q(destination=destination, basket_id=basket_id), Q.OR)
if destination:
q.add(Q(destination=destination, basket_id=''), Q.OR)
if basket_id:
q.add(Q(destination=None, basket_id=basket_id), Q.OR)
qrs = models.ShippingRate.objects.filter(name=name).filter(q)
count = qrs.count()
if count == 1:
shipping_rate_qrs = qrs[0]
shipping_rate = {
"rate": shipping_rate_qrs.rate,
"description": shipping_rate_qrs.description,
"carrier": shipping_rate_qrs.carrier}
if not shipping_rate:
if invalid_country:
raise InvalidShippingCountry
raise InvalidShippingRate()
return shipping_rate
示例14: apply_filters_to_queryset
# 需要导入模块: from django.db.models import Q [as 别名]
# 或者: from django.db.models.Q import OR [as 别名]
def apply_filters_to_queryset(qs, filters):
# first we do a schema check since trying to fetch unused tags will cause a DB error
valid_tags = []
with connections['crate'].cursor() as c:
sql = """SELECT column_name from information_schema.columns
WHERE table_name = 'topic' and column_name like 'kv_tags[%';"""
c.execute(sql)
for (cn, ) in c:
# extract the tag name from "kv_tags['tag_name']"
valid_tags.append(cn[9:-2])
# ordering or AND and OR filters
# A or B and C -> (A(qs) | B(qs)) & C(qs)
# A or B and C or D -> (A(qs) | B(qs)) & (C(qs) | D(qs))
# so we first resolve the ORs from the list:
# (A, *), (B, or), (C, and), (D, or)
# The ORs apply to oqs (original qs)
# then we AND each resulting qs
oqs = qs
first = True
rqs = []
for (filter_field, filter_type, filter_value, filter_op) in filters:
logging.info('apply_filters_to_queryset: add filter %s', (filter_field, filter_type, filter_value, filter_op))
if first:
qs = apply_filter_to_queryset(oqs, filter_field, filter_type, filter_value, valid_tags)
elif filter_op and filter_op.lower() == 'or':
qs = qs | apply_filter_to_queryset(oqs, filter_field, filter_type, filter_value, valid_tags)
else:
# skip for now store the current qs
rqs.append(qs)
# reset working qs
qs = oqs
qs = apply_filter_to_queryset(oqs, filter_field, filter_type, filter_value, valid_tags)
first = False
# add the last qs
rqs.append(qs)
# now AND resulting qs
qs = oqs
for q in rqs:
qs = qs & q
return qs