本文整理汇总了Python中django.db.models.sql.constants.LOOKUP_SEP.join方法的典型用法代码示例。如果您正苦于以下问题:Python LOOKUP_SEP.join方法的具体用法?Python LOOKUP_SEP.join怎么用?Python LOOKUP_SEP.join使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.sql.constants.LOOKUP_SEP
的用法示例。
在下文中一共展示了LOOKUP_SEP.join方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _chemicalite_filter
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def _chemicalite_filter(self, args, original_kwargs):
chemicalite = connections[self.db].ops
opts = self.query.get_meta()
args = list(args)
kwargs = {}
for lookup, value in original_kwargs.items():
parts = lookup.split(LOOKUP_SEP)
if len(parts) == 1 or parts[-1] not in self.query.query_terms:
lookup_type = 'exact'
else:
lookup_type = parts.pop()
chemfield = _ChemWhereNode._check_chem_field(opts,
LOOKUP_SEP.join(parts))
if (lookup_type in chemicalite.structure_operators and
chemfield and isinstance(chemfield, _MoleculeField)):
stridx_attname = chemfield.stridx_attname
stridx_lookup_type = chemicalite.stridx_lookup[lookup_type]
stridx_parts = (parts[:-1] +
[stridx_attname, stridx_lookup_type])
stridx_lookup = LOOKUP_SEP.join(stridx_parts)
args.extend((Q(**{lookup: value}),
Q(**{stridx_lookup: value})))
else:
kwargs[lookup] = value
return tuple(args), kwargs
示例2: _get_join_paths
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def _get_join_paths(self, table_alias, accessor_path):
try:
model_class = self.queryset._get_model_class_from_table(table_alias)
except CacheBotException:
# this is a many to many field
try:
model_class = [f.rel.to for m in get_models() for f in m._meta.local_many_to_many if f.m2m_db_table() == table_alias][0]
except:
import ipdb; ipdb.set_trace()
accessor_path = model_class._meta.pk.attname
yield model_class, accessor_path
join_from_tables = ifilter(lambda x: x[1] == table_alias, self.queryset.query.join_map.keys())
for join_tuple in join_from_tables:
if join_tuple[0]:
for model_class, join_accessor_path in self._get_join_paths(join_tuple[0], join_tuple[2]):
if join_accessor_path == model_class._meta.pk.attname:
for attname, related in self.queryset._get_reverse_relations(model_class):
join_accessor_path = attname
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
elif join_accessor_path.split(LOOKUP_SEP)[-1] == 'id':
accessor_path_split = join_accessor_path.split(LOOKUP_SEP)
join_accessor_path = LOOKUP_SEP.join(accessor_path_split[:-1])
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
elif join_accessor_path.endswith('_id'):
join_accessor_path = join_accessor_path[:-3]
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
else:
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
示例3: patch_child
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def patch_child(self, parts, lookup, value):
inherited_flag = ["is_%s_inherited" % parts[-1]]
inherited_value = ["%s_value" % parts[-1]]
lookup = [lookup] if lookup else []
is_inherited = LOOKUP_SEP.join(parts[:-1] + inherited_flag)
field = LOOKUP_SEP.join(parts[:-1] + inherited_value + lookup)
print is_inherited
print field
return Q(**{is_inherited: False, field: value})
示例4: lookup_allowed
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def lookup_allowed(self, lookup, value):
# overriden to allow filter on cell_filter fields
# import django.contrib.admin.options
# django.contrib.admin.options.QUERY_TERMS.update({'not':'not'})
original = DjangoModelAdmin.lookup_allowed(self, lookup, value)
if original:
return True
model = self.model
parts = lookup.split(LOOKUP_SEP)
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
clean_lookup = LOOKUP_SEP.join(parts)
flat_filter = [isinstance(v, tuple) and v[0] or v for v in self.list_filter]
flat_filter.extend([isinstance(v, tuple) and v[0] or v for v in self.cell_filter])
return clean_lookup in self.extra_allowed_filter or clean_lookup in flat_filter
示例5: get_queryset
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def get_queryset(self, request, **resources):
if self.queryset is None:
return None
# Make filters from URL variables or resources
filters = dict((k, v) for k, v in resources.iteritems() if k in self.meta.model_fields)
qs = self.queryset.filter(**filters)
# Make filters from GET variables
for field in request.GET.iterkeys():
tokens = field.split(LOOKUP_SEP)
field_name = tokens[0]
if not field_name in self.meta.model_fields or filters.has_key(field_name):
continue
converter = self.model._meta.get_field(field).to_python if len(tokens) == 1 else lambda v: v
value = map(converter, request.GET.getlist(field))
if len(value) > 1:
tokens.append('in')
else:
value = value.pop()
try:
qs = qs.filter(**{LOOKUP_SEP.join(tokens): value})
except FieldError, e:
logger.warning(e)
示例6: _get_reverse_relations
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def _get_reverse_relations(self, model_class):
for related in chain(model_class._meta.get_all_related_objects(), model_class._meta.get_all_related_many_to_many_objects()):
if related.opts.db_table in self.query.tables:
related_name = related.get_accessor_name()
yield related_name, related
for attname, join_related in self._get_reverse_relations(related.model):
yield LOOKUP_SEP.join((related_name + '_cache', attname)), join_related
示例7: reverse_field_path
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def reverse_field_path(model, path):
""" Create a reversed field path.
E.g. Given (Order, "user__groups"),
return (Group, "user__order").
Final field must be a related model, not a data field.
"""
reversed_path = []
parent = model
pieces = path.split(LOOKUP_SEP)
for piece in pieces:
field, model, direct, m2m = parent._meta.get_field_by_name(piece)
# skip trailing data field if extant:
if len(reversed_path) == len(pieces)-1: # final iteration
try:
get_model_from_relation(field)
except NotRelationField:
break
if direct:
related_name = field.related_query_name()
parent = field.rel.to
else:
related_name = field.field.name
parent = field.model
reversed_path.insert(0, related_name)
return (parent, LOOKUP_SEP.join(reversed_path))
示例8: get_filters
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def get_filters(self, request, **resources):
" Make filters from GET variables. "
filters = dict()
for field in request.GET.iterkeys():
tokens = field.split(LOOKUP_SEP)
field_name = tokens[0]
exclude = False
if tokens[-1] == 'not':
exclude = True
tokens.pop()
if not field_name in self.meta.model_fields:
continue
converter = self.model._meta.get_field(
field_name).to_python if len(tokens) == 1 else lambda v: v
value = map(converter, request.GET.getlist(field))
if len(value) > 1:
tokens.append('in')
else:
value = value.pop()
filters[LOOKUP_SEP.join(tokens)] = (value, exclude)
return filters
示例9: apply_sorting
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def apply_sorting(self, obj_list, options=None):
"""
Given a dictionary of options, apply some ORM-level sorting to the
provided ``QuerySet``.
Looks for the ``order_by`` key and handles either ascending (just the
field name) or descending (the field name with a ``-`` in front).
The field name should be the resource field, **NOT** model field.
"""
if options is None:
options = {}
parameter_name = 'order_by'
if not 'order_by' in options:
if not 'sort_by' in options:
# Nothing to alter the order. Return what we've got.
return obj_list
else:
warnings.warn("'sort_by' is a deprecated parameter. Please use 'order_by' instead.")
parameter_name = 'sort_by'
order_by_args = []
if hasattr(options, 'getlist'):
order_bits = options.getlist(parameter_name)
else:
order_bits = options.get(parameter_name)
if not isinstance(order_bits, (list, tuple)):
order_bits = [order_bits]
for order_by in order_bits:
order_by_bits = order_by.split(LOOKUP_SEP)
field_name = order_by_bits[0]
order = ''
if order_by_bits[0].startswith('-'):
field_name = order_by_bits[0][1:]
order = '-'
if not field_name in self.fields:
# It's not a field we know about. Move along citizen.
raise InvalidSortError("No matching '%s' field for ordering on." % field_name)
if not field_name in self._meta.ordering:
raise InvalidSortError("The '%s' field does not allow ordering." % field_name)
if self.fields[field_name].attribute is None:
raise InvalidSortError("The '%s' field has no 'attribute' for ordering with." % field_name)
order_by_args.append("%s%s" % (order, LOOKUP_SEP.join([self.fields[field_name].attribute] + order_by_bits[1:])))
reverse = False
if order == '-': reverse = True
ordered_list = sorted(obj_list, key= attrgetter(field_name), reverse=reverse)
return ordered_list
示例10: patch_parent
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def patch_parent(self, parts, lookup, value):
_parts = parts[:]
last_field_name, model = self.traverse_models(_parts, self.model)
lookup = [lookup] if lookup else []
parents_name, parents_field_name = model.FIELD_INHERITANCE_MAP[last_field_name]
parent_lookup = LOOKUP_SEP.join(parts[:-1] + [parents_name] + [parents_field_name] + lookup)
print parent_lookup
return Q(**{parent_lookup: value})
示例11: build_filters
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def build_filters(self, filters=None):
"""
Given a dictionary of filters, create the necessary ORM-level filters.
Keys should be resource fields, **NOT** model fields.
Valid values are either a list of Django filter types (i.e.
``['startswith', 'exact', 'lte']``), the ``ALL`` constant or the
``ALL_WITH_RELATIONS`` constant.
"""
# At the declarative level:
# filtering = {
# 'resource_field_name': ['exact', 'startswith', 'endswith', 'contains'],
# 'resource_field_name_2': ['exact', 'gt', 'gte', 'lt', 'lte', 'range'],
# 'resource_field_name_3': ALL,
# 'resource_field_name_4': ALL_WITH_RELATIONS,
# ...
# }
# Accepts the filters as a dict. None by default, meaning no filters.
if filters is None:
filters = {}
qs_filters = {}
for filter_expr, value in filters.items():
filter_bits = filter_expr.split(LOOKUP_SEP)
field_name = filter_bits.pop(0)
filter_type = 'exact'
if not field_name in self.fields:
# It's not a field we know about. Move along citizen.
continue
if len(filter_bits) and filter_bits[-1] in QUERY_TERMS.keys():
filter_type = filter_bits.pop()
lookup_bits = self.check_filtering(field_name, filter_type, filter_bits)
if value in ['true', 'True', True]:
value = True
elif value in ['false', 'False', False]:
value = False
elif value in ('nil', 'none', 'None', None):
value = None
# Split on ',' if not empty string and either an in or range filter.
if filter_type in ('in', 'range') and len(value):
if hasattr(filters, 'getlist'):
value = filters.getlist(filter_expr)
else:
value = value.split(',')
db_field_name = LOOKUP_SEP.join(lookup_bits)
qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
qs_filters[qs_filter] = value
return dict_strip_unicode_keys(qs_filters)
示例12: lookup_allowed
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def lookup_allowed(self, lookup, value):
# overriden to allow filter on cell_filter fields
# import django.contrib.admin.options
# django.contrib.admin.options.QUERY_TERMS.update({'not':'not'})
original = super(IModelAdmin, self).lookup_allowed(lookup, value)
if original:
return True
parts = lookup.split(LOOKUP_SEP)
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.extra_allowed_filter
示例13: _get_join_paths
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def _get_join_paths(self, table_alias, accessor_path):
model_class, m2m = self.queryset._get_model_class_from_table(table_alias)
if m2m:
accessor_path = model_class._meta.pk.attname
yield model_class, accessor_path
for join_tuple in self.queryset.query.join_map.keys():
if join_tuple[0] and join_tuple[1] == table_alias:
for model_class, join_accessor_path in self._get_join_paths(join_tuple[0], join_tuple[2]):
if join_accessor_path == model_class._meta.pk.attname:
for attname, related in self.queryset._get_reverse_relations(model_class):
join_accessor_path = attname
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
elif join_accessor_path.split(LOOKUP_SEP)[-1] == 'id':
accessor_path_split = join_accessor_path.split(LOOKUP_SEP)
join_accessor_path = LOOKUP_SEP.join(accessor_path_split[:-1])
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
elif join_accessor_path.endswith('_id'):
join_accessor_path = join_accessor_path[:-3]
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
else:
yield model_class, LOOKUP_SEP.join((join_accessor_path, accessor_path))
示例14: _expand_money_params
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def _expand_money_params(kwargs):
from moneyed import Money
from django.db.models.sql.constants import LOOKUP_SEP, QUERY_TERMS
to_append = {}
for name, value in kwargs.items():
if isinstance(value, Money):
# Get rid of __lt, __gt etc for the currency lookup
path = name.split(LOOKUP_SEP)
if QUERY_TERMS.has_key(path[-1]):
clean_name = LOOKUP_SEP.join(path[:-1])
else:
clean_name = name
to_append[name] = value.amount
to_append[currency_field_name(clean_name)] = smart_unicode(value.currency)
kwargs.update(to_append)
return kwargs
示例15: lookup_allowed
# 需要导入模块: from django.db.models.sql.constants import LOOKUP_SEP [as 别名]
# 或者: from django.db.models.sql.constants.LOOKUP_SEP import join [as 别名]
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
try:
self.model._meta.get_field_by_name(parts[0])
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
else:
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy