本文整理汇总了Python中django.db.models.fields.FieldDoesNotExist方法的典型用法代码示例。如果您正苦于以下问题:Python fields.FieldDoesNotExist方法的具体用法?Python fields.FieldDoesNotExist怎么用?Python fields.FieldDoesNotExist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.fields
的用法示例。
在下文中一共展示了fields.FieldDoesNotExist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _restrict_fields_choices
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def _restrict_fields_choices(self, model, organization, fields):
for source in fields:
field, m, direct, m2m = model._meta.get_field_by_name(source)
rel = field.rel
if not rel:
# next field
continue
rel_model = rel.to
try:
rel_model._meta.get_field_by_name(self.relation_name)
except FieldDoesNotExist:
# next field
continue
form_field = fields[source]
form_field.queryset = (form_field.choices.queryset
.filter(**{self.relation_name: organization}))
示例2: get_queryset
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def get_queryset(self):
queryset = super().get_queryset()
queryset = (queryset
.select_related(
'organization')
.prefetch_related(
'lines',
'lines__tax_rate'))
try:
# to raise the exception
self.model._meta.get_field_by_name('client')
queryset = queryset.select_related('client')
except FieldDoesNotExist:
pass
try:
# to raise the exception
self.model._meta.get_field_by_name('payments')
queryset = queryset.prefetch_related('payments')
except FieldDoesNotExist:
pass
return queryset
示例3: check_field_exists
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def check_field_exists(self, field_name: str):
"""Implements field exists check for debugging purposes.
:param field_name:
"""
if not settings.DEBUG:
return
try:
self.lookup_opts.get_field(field_name)
except FieldDoesNotExist as e:
raise AdmirarchyConfigurationError(e)
########################################################
示例4: serializable_value
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field_by_name(field_name)[0]
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
示例5: get_field_by_name
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def get_field_by_name(self, name):
"""
Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
'direct' is False, 'field_object' is the corresponding RelatedObject
for this field (since the field doesn't have an instance associated
with it).
Uses a cache internally, so after the first access, this is very fast.
"""
try:
try:
return self._name_map[name]
except AttributeError:
cache = self.init_name_map()
return cache[name]
except KeyError:
raise FieldDoesNotExist('%s has no field named %r'
% (self.object_name, name))
示例6: get_ordering_field
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def get_ordering_field(self, field_name):
"""
Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the 'admin_order_field' attribute. Returns None if no
proper model field name can be matched.
"""
try:
field = self.opts.get_field(field_name)
return field.name
except FieldDoesNotExist:
# See whether field_name is a name of a non-field
# that allows sorting.
if callable(field_name):
attr = field_name
elif hasattr(self.model_admin, field_name):
attr = getattr(self.model_admin, field_name)
else:
attr = getattr(self.model, field_name)
return getattr(attr, 'admin_order_field', None)
示例7: render
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def render(self, context):
# Let any VariableDoesNotExist raised bubble up
args = [self.node.resolve(context)]
if self.foreign_key is not None:
app_label, model_name, fk_attr = self.foreign_key.split('.')
cls = apps.get_model(app_label, model_name)
if cls is None:
raise template.TemplateSyntaxError(
_('drilldown_tree_for_node tag was given an invalid model: %s') %
'.'.join([app_label, model_name])
)
try:
cls._meta.get_field(fk_attr)
except FieldDoesNotExist:
raise template.TemplateSyntaxError(
_('drilldown_tree_for_node tag was given an invalid model field: %s') % fk_attr
)
args.extend([cls, fk_attr, self.count_attr, self.cumulative])
context[self.context_var] = drilldown_tree_for_node(*args)
return ''
示例8: _get_field_or_method_label
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def _get_field_or_method_label(self, model, field_name):
resource_label = self._get_resource_label(model, field_name)
if resource_label is not None:
return resource_label
else:
try:
field = model._meta.get_field(field_name)
if field.auto_created and (field.one_to_many or field.many_to_many):
return (
getattr(field.field, 'reverse_verbose_name', None) or
field.related_model._meta.verbose_name_plural
)
elif field.auto_created and field.one_to_one:
return (
getattr(field.field, 'reverse_verbose_name', None) or
field.related_model._meta.verbose_name
)
else:
return field.verbose_name
except FieldDoesNotExist:
method = get_class_method(model, field_name)
return getattr(method, 'short_description', pretty_name(field_name))
示例9: field_verbose_name
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def field_verbose_name(model, name):
try:
field = model._meta.get_field(name)
except FieldDoesNotExist:
return ''
else:
return field.verbose_name
示例10: get_un_soft_deleted_objects
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def get_un_soft_deleted_objects(self, collector):
'''filter all those objects from collector which are already
soft-deleted'''
for model, instances in collector.data.items():
try:
if model._meta.get_field("deleted"):
collector.data[model] = set(filter(lambda x: not x.deleted,
instances))
except FieldDoesNotExist:
# if deleted field does not exist in model, do nothing
pass
return collector
示例11: ensure_default_manager
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def ensure_default_manager(sender, **kwargs):
"""
Ensures that a Model subclass contains a default manager and sets the
_default_manager attribute on the class. Also sets up the _base_manager
points to a plain Manager instance (which could be the same as
_default_manager if it's not a subclass of Manager).
"""
cls = sender
if cls._meta.abstract:
setattr(cls, 'objects', AbstractManagerDescriptor(cls))
return
elif cls._meta.swapped:
setattr(cls, 'objects', SwappedManagerDescriptor(cls))
return
if not getattr(cls, '_default_manager', None):
# Create the default manager, if needed.
try:
cls._meta.get_field('objects')
raise ValueError("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__)
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
cls._base_manager = cls.objects
elif not getattr(cls, '_base_manager', None):
default_mgr = cls._default_manager.__class__
if (default_mgr is Manager or
getattr(default_mgr, "use_for_related_fields", False)):
cls._base_manager = cls._default_manager
else:
# Default manager isn't a plain Manager class, or a suitable
# replacement, so we walk up the base class hierarchy until we hit
# something appropriate.
for base_class in default_mgr.mro()[1:]:
if (base_class is Manager or
getattr(base_class, "use_for_related_fields", False)):
cls.add_to_class('_base_manager', base_class())
return
raise AssertionError("Should never get here. Please report a bug, including your model and model manager setup.")
示例12: __get__
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def __get__(self, instance, owner):
"""
Retrieves and caches the value from the datastore on the first lookup.
Returns the cached value.
"""
from django.db.models.fields import FieldDoesNotExist
non_deferred_model = instance._meta.proxy_for_model
opts = non_deferred_model._meta
assert instance is not None
data = instance.__dict__
if data.get(self.field_name, self) is self:
# self.field_name is the attname of the field, but only() takes the
# actual name, so we need to translate it here.
try:
f = opts.get_field_by_name(self.field_name)[0]
except FieldDoesNotExist:
f = [f for f in opts.fields
if f.attname == self.field_name][0]
name = f.name
# Lets see if the field is part of the parent chain. If so we
# might be able to reuse the already loaded value. Refs #18343.
val = self._check_parent_chain(instance, name)
if val is None:
# We use only() instead of values() here because we want the
# various data coersion methods (to_python(), etc.) to be
# called here.
val = getattr(
non_deferred_model._base_manager.only(name).using(
instance._state.db).get(pk=instance.pk),
self.field_name
)
data[self.field_name] = val
return data[self.field_name]
示例13: get_field
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def get_field(self, name, many_to_many=True):
"""
Returns the requested field by name. Raises FieldDoesNotExist on error.
"""
to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
for f in to_search:
if f.name == name:
return f
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
示例14: prepare_leaf
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def prepare_leaf(self, node, query, allow_joins):
if not allow_joins and LOOKUP_SEP in node.name:
raise FieldError("Joined field references are not permitted in this query")
field_list = node.name.split(LOOKUP_SEP)
if (len(field_list) == 1 and
node.name in query.aggregate_select.keys()):
self.contains_aggregate = True
self.cols.append((node, query.aggregate_select[node.name]))
else:
try:
dupe_multis = False if self.reuse is None else True
field, source, opts, join_list, last, _ = query.setup_joins(
field_list, query.get_meta(), query.get_initial_alias(),
dupe_multis, can_reuse=self.reuse)
col, _, join_list = query.trim_joins(source, join_list, last, False)
if self.reuse is not None:
self.reuse.update(join_list)
self.cols.append((node, (join_list[-1], col)))
except FieldDoesNotExist:
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (self.name,
[f.name for f in self.opts.fields]))
##################################################
# Vistor methods for final expression evaluation #
##################################################
示例15: has_related_field_in_list_display
# 需要导入模块: from django.db.models import fields [as 别名]
# 或者: from django.db.models.fields import FieldDoesNotExist [as 别名]
def has_related_field_in_list_display(self):
for field_name in self.list_display:
try:
field = self.opts.get_field(field_name)
except FieldDoesNotExist:
pass
else:
if isinstance(field, models.ManyToOneRel):
return True
return False