def __deepcopy__(self, memo): import django.utils.copycompat as copy result = self.__class__('', mutable=True, encoding=self.encoding) memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result
def _translate_queries (self, *a, **kw) : if not kw and len(a) < 2 and isinstance(a[0], Q, ) : _query = deepcopy(a[0]) else : _query = Q(*a, **kw) _query_new = deepcopy(_query, ) _query_new.children = list() _content_object = None for i in range(len(_query.children, ), ) : _q = _query.children[i] if isinstance(_q, Q, ) : _q = self._translate_queries(_q, ) elif isinstance(_q, tuple, ) : pass else : # it must be content_object _content_object = _q continue _query_new.children.append(_q, ) if _content_object : _query_new = self._translate_query(_content_object, _query_new, ) return _query_new
def __deepcopy__(self, memodict): """ Utility method used by copy.deepcopy(). """ obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = deepcopy(self.children, memodict) obj.subtree_parents = deepcopy(self.subtree_parents, memodict) return obj
def __deepcopy__(self, memo=None): import django.utils.copycompat as copy if memo is None: memo = {} result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result
def test_deepcopy(self): # Check that we *can* do deep copy, and that it returns the right # objects. # First, for an unevaluated SimpleLazyObject s = SimpleLazyObject(complex_object) assert s._wrapped is None s2 = copy.deepcopy(s) assert s._wrapped is None # something has gone wrong is s is evaluated self.assertEqual(s2, complex_object()) # Second, for an evaluated SimpleLazyObject name = s.name # evaluate assert s._wrapped is not None s3 = copy.deepcopy(s) self.assertEqual(s3, complex_object())
def visible(self, request): if request.user.is_superuser: return self.get_query_set() q = deepcopy(self.Q) self.set_values(q, request) queryset = self.get_query_set().filter(q).distinct() return queryset
def js_options(self): options = deepcopy(self._meta.options) columns = self.bound_columns aoColumnDefs = options.setdefault('aoColumnDefs', []) colopts = SortedDict() for index, name in enumerate(columns.keys()): column = columns[name] for key, value in column.options.items(): if not (key, str(value)) in colopts.keys(): colopts[(key, str(value))] = {} colopts[(key, str(value))]['targets'] = [] colopts[(key, str(value))]['targets'] = colopts[(key, str(value))]['targets'] + [index] colopts[(key, str(value))]['key'] = key colopts[(key, str(value))]['value'] = value if column.sort_field != column.display_field and column.sort_field in columns: key = 'iDataSort' value = columns.keys().index(column.sort_field) if not (key, str(value)) in colopts.keys(): colopts[(key, str(value))] = {} colopts[(key, str(value))]['targets'] = [] colopts[(key, str(value))]['targets'] = colopts[(key, str(value))]['targets'] + [index] colopts[(key, str(value))]['key'] = key colopts[(key, str(value))]['value'] = value for kv, values in colopts.items(): aoColumnDefs.append(dict([(values['key'], values['value']), ('aTargets', values['targets'])])) options['sAjaxSource'] = reverse_ajax_source(options.get('sAjaxSource')) return mark_safe(dumpjs(options, indent=4, sort_keys=True))
def __new__(cls, name, bases, attrs): attrs['base_fields'] = {} declared_fields = {} try: parents = [b for b in bases if issubclass(b, Entity)] parents.reverse() for p in parents: parent_fields = getattr(p, 'base_fields', {}) for field_name, field_object in parent_fields.items(): attrs['base_fields'][field_name] = deepcopy(field_object) except NameError: pass for field_name, obj in attrs.items(): if isinstance(obj, fields.ApiField) and \ not field_name.startswith('_'): field = attrs.pop(field_name) field.field_name = field_name declared_fields[field_name] = field attrs['base_fields'].update(declared_fields) attrs['declared_fields'] = declared_fields new_class = super( EntityMetaclass, cls).__new__(cls, name, bases, attrs) for field_name, field_object in new_class.base_fields.items(): if hasattr(field_object, 'contribute_to_class'): field_object.contribute_to_class(new_class, field_name) return new_class
def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=":", empty_permitted=False, ): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} self.auto_id = auto_id self.prefix = prefix self.initial = initial or {} self.error_class = error_class self.label_suffix = label_suffix self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. self._changed_data = None # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = deepcopy(self.base_fields)
def __init__(self, data=None, **kwargs): self.simple_lookups = [] self.complex_conditions = [] self.extra_conditions = Extra() use_filter_chaining = kwargs.pop('use_filter_chaining', None) if use_filter_chaining is None: use_filter_chaining = self.use_filter_chaining self.filter = self.filter_chaining \ if use_filter_chaining else self.filter_bulk if hasattr(self, 'filter_specs') and isinstance(self.filter_specs, tuple): self.filter_specs = dict( (fs.field_name, fs) for fs in self.filter_specs ) else: self.filter_specs = deepcopy(self.filter_specs_base) self.runtime_context = kwargs.pop('runtime_context', {}) super(FilterFormBase, self).__init__(data=data, **kwargs) # Generate form fields for name, spec in self.filter_specs.iteritems(): if isinstance(spec.filter_field, forms.Field): self.fields[name] = spec.filter_field else: field_cls, local_field_kwargs = spec.filter_field field_kwargs = self.default_fields_args.copy() field_kwargs.update(local_field_kwargs) self.fields[name] = field_cls(**field_kwargs) self.spec_count = len(self.filter_specs)
def __init__(self, datatable, column, name): self.datatable = datatable self.column = column self.name = name self.options = deepcopy(self.column.options) for key in self.column.DEFAULTS.keys(): setattr(self, key, getattr(self.column, key)) if self.id is None: self.id = '%s-%s' % (self.datatable.id, self.name) self.classes = set(self.classes) self.classes.add('datatable_col_%s' % self.name) if self.label is None: self.label = self.name.replace('_', ' ').title() if self.model_field is None: self.model_field = self.name self.model_field = self.model_field.replace('.', '__') if self.display_field is None: self.display_field = self.model_field self.display_field = self.display_field.replace('.', '__') if self.sort_field is None: self.sort_field = self.model_field self.sort_field = self.sort_field.replace('.', '__') if self.search_field is None: self.search_field = self.model_field self.search_field = self.search_field.replace('.', '__')
def __new__(cls, name, bases, attrs): attrs['base_fields'] = {} declared_fields = {} try: parents = [b for b in bases if issubclass(b, Entity)] parents.reverse() for p in parents: parent_fields = getattr(p, 'base_fields', {}) for field_name, field_object in parent_fields.items(): attrs['base_fields'][field_name] = deepcopy(field_object) except NameError: pass for field_name, obj in attrs.items(): if isinstance(obj, fields.ApiField) and \ not field_name.startswith('_'): field = attrs.pop(field_name) field.field_name = field_name declared_fields[field_name] = field attrs['base_fields'].update(declared_fields) attrs['declared_fields'] = declared_fields new_class = super(EntityMetaclass, cls).__new__(cls, name, bases, attrs) for field_name, field_object in new_class.base_fields.items(): if hasattr(field_object, 'contribute_to_class'): field_object.contribute_to_class(new_class, field_name) return new_class
def __init__(self, align='left'): self.entries = deepcopy(self.base_entries) self.align = align # Increase the creation counter, and save our local copy. self.creation_counter = BaseNav.creation_counter BaseNav.creation_counter += 1
def __init__(self, api_name=None, resource_name=None, data={}): self.queryset = getattr(self._meta, 'queryset', None) self.api_name = api_name or '' self.resource_name = resource_name or '' # Introspect the model, adding/removing fields as needed. # Adds/Excludes should happen only if the fields are not already # defined in `self.fields`. self.instance = None if self.queryset is None: raise ImproperlyConfigured("Using the ModelRepresentation requires providing a model.") self.object_class = self.queryset.model self.fields = deepcopy(self.base_fields) if getattr(self._meta, 'include_resource_uri', True) and not 'resource_uri' in self.fields: self.fields['resource_uri'] = CharField(readonly=True) fields = getattr(self._meta, 'fields', []) excludes = getattr(self._meta, 'excludes', []) # Add in the new fields. self.fields.update(self.get_fields(fields, excludes)) # Now that we have fields, populate fields via kwargs if found. for key, value in data.items(): if key in self.fields: self.fields[key].value = value if self.object_class is None: raise ImproperlyConfigured("Using the Representation requires providing an object_class in the inner Meta class.")
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} self.auto_id = auto_id self.prefix = prefix self.initial = initial or {} self.error_class = error_class self.label_suffix = label_suffix self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. self._changed_data = None # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = deepcopy(self.base_fields)
def test22_copy(self): "Testing use with the Python `copy` module." import django.utils.copycompat as copy poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))') cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr)
def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj_dict = deepcopy(self.__dict__, memo) obj_dict['_iter'] = None obj = self.__class__() obj.__dict__.update(obj_dict) return obj
def getRecipeModelFromForm(recipe, request): recipe = deepcopy(recipe) del recipe.cleaned_data['ingredients'] del recipe.cleaned_data['directions'] del recipe.cleaned_data['image'] parts = recipe.cleaned_data['category'].split('-') recipe.cleaned_data['category'] = parts[0] recipe.cleaned_data['subcategory'] = parts[1] recipe.cleaned_data['owner'] = request.user.uid return models.Recipe(**recipe.cleaned_data)
def benchmark_multi(): #instantiate a new MultiValueDict and call key method (i.e. that do something diff than dict) caseDict = MultiValueDict(case) caseDict['a'] caseDict['b'] caseDict['c'] caseDict.update(update) copy.copy(caseDict) copy.deepcopy(caseDict) caseDict.items() caseDict.lists() for i in caseDict: i caseDict['a'] = 'A' caseDict['b'] = 'B' caseDict['c'] = 'C'
def benchmark_dict(): #instantiate a new dict and call same methods as above - to be fair, get unlistify in this method where required caseDict = dict(case) caseDict['a'][0] caseDict['b'][1] caseDict['c'][2] caseDict.items() caseDict.values() for i in caseDict: i caseDict.update(update) copy.copy(caseDict) copy.deepcopy(caseDict) caseDict['a'] = ['A'] caseDict['b'] = ['B'] caseDict['c'] = ['C']
def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj = self.__class__() for k,v in self.__dict__.items(): if k in ('_iter','_result_cache'): obj.__dict__[k] = None else: obj.__dict__[k] = deepcopy(v, memo) return obj
def __init__(self, user, options): """ Params: user: The id of the app user. options: A dictionary of cookbook options derived from a CookbookData form. """ options = deepcopy(options) self.recipe_ids = options['recipes'] del options['recipes'] self.options = options self.user = user
def translate_query (query, func=lambda x : x, ) : _query = deepcopy(query, ) for i in range(len(_query.children, ), ) : _q = _query.children[i] if isinstance(_q, Q, ) : _q = translate_query(_q, func=func, ) elif isinstance(_q, tuple, ) : _q = func(_q, ) _query.children[i] = _q return _query
def __init__(self, request=None, context={}, name=""): if name: self.name = unicode(name) if not hasattr(self, "view"): self.view = self.name self.panes = deepcopy(self.base_panes) self.first_pane = self._gen_first_pane() self.current_pane = self.first_pane self.request = request self.context = context self._trigger_name = None self._type = None
def __deepcopy__(self, memo): if self._wrapped is None: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result else: # Changed to use deepcopy from copycompat, instead of copy # For Python 2.4. from django.utils.copycompat import deepcopy return deepcopy(self._wrapped, memo)
def __init__(self, api_name=None, resource_name=None, data={}): self.object_class = getattr(self._meta, 'object_class', None) self.instance = None self.api_name = api_name or '' self.resource_name = resource_name or '' # Use a copy of the field instances, not the ones actually stored on # the class. self.fields = deepcopy(self.base_fields) if getattr(self._meta, 'include_resource_uri', True) and not 'resource_uri' in self.fields: self.fields['resource_uri'] = CharField(readonly=True) # Now that we have fields, populate fields via kwargs if found. for key, value in data.items(): if key in self.fields: self.fields[key].value = value if self.object_class is None: raise ImproperlyConfigured("Using the Representation requires providing an object_class in the inner Meta class.")
def __init__(self, data=None, **kwargs): self.complex_conditions = [] if hasattr(self, 'filter_specs') and isinstance(self.filter_specs, tuple): self.filter_specs = dict( (fs.field_name, fs) for fs in self.filter_specs ) else: self.filter_specs = deepcopy(self.filter_specs_base) view_kwargs = kwargs.pop('view_kwargs', {}) super(FilterForm, self).__init__(data=data, **kwargs) # Generate form fields for name, spec in self.filter_specs.iteritems(): field_cls, local_field_kwargs = spec.filter_field field_kwargs = self.default_fields_args.copy() field_kwargs.update(local_field_kwargs) if field_kwargs.has_key('view_kwargs'): field_kwargs['view_kwargs'] = view_kwargs self.fields[name] = field_cls(**field_kwargs) self.spec_count = len(self.filter_specs)
def __new__(cls, name, bases, attrs): attrs['base_fields'] = {} declared_fields = {} # Inherit any fields from parent(s). try: parents = [b for b in bases if issubclass(b, Resource)] for p in parents: fields = getattr(p, 'base_fields', {}) for field_name, field_object in fields.items(): attrs['base_fields'][field_name] = deepcopy(field_object) except NameError: pass for field_name, obj in attrs.items(): if isinstance(obj, ApiField): field = attrs.pop(field_name) declared_fields[field_name] = field attrs['base_fields'].update(declared_fields) attrs['declared_fields'] = declared_fields new_class = super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs) opts = getattr(new_class, 'Meta', None) new_class._meta = options.ResourceOptions(opts) if getattr(new_class._meta, 'include_resource_uri', True): if not 'resource_uri' in new_class.base_fields: new_class.base_fields['resource_uri'] = CharField( readonly=True) elif 'resource_uri' in new_class.base_fields and not 'resource_uri' in attrs: del (new_class.base_fields['resource_uri']) for field_name, field_object in new_class.base_fields.items(): if hasattr(field_object, 'contribute_to_class'): field_object.contribute_to_class(new_class, field_name) return new_class
def __new__(cls, name, bases, attrs): attrs["base_fields"] = {} declared_fields = {} # Inherit any fields from parent(s). try: parents = [b for b in bases if issubclass(b, Resource)] for p in parents: fields = getattr(p, "base_fields", {}) for field_name, field_object in fields.items(): attrs["base_fields"][field_name] = deepcopy(field_object) except NameError: pass for field_name, obj in attrs.items(): if isinstance(obj, ApiField): field = attrs.pop(field_name) declared_fields[field_name] = field attrs["base_fields"].update(declared_fields) attrs["declared_fields"] = declared_fields new_class = super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs) opts = getattr(new_class, "Meta", None) new_class._meta = options.ResourceOptions(opts) if getattr(new_class._meta, "include_resource_uri", True): if not "resource_uri" in new_class.base_fields: new_class.base_fields["resource_uri"] = CharField(readonly=True) elif "resource_uri" in new_class.base_fields and not "resource_uri" in attrs: del (new_class.base_fields["resource_uri"]) for field_name, field_object in new_class.base_fields.items(): if hasattr(field_object, "contribute_to_class"): field_object.contribute_to_class(new_class, field_name) return new_class
def __init__(self, data=None, *args, **kwargs): # Extract the data for the translated fields for passing to # the translation form translated_data = None if data: translated_data = {} for key, value in data.iteritems(): if key in self._meta.translated_fields: translated_data[key] = value if not len(translated_data): # If none of the translated fields were passed as data, # set translated_data back to None so the translation form # will be unbound translated_data = None super(TranslatedModelForm, self).__init__(data, *args, **kwargs) self._translation_model_form_class = modelform_factory( self._meta.model.translation_class, fields=self._meta.translated_fields) self._translation_form = self._translation_model_form_class( translated_data, instance=self._get_initial_translation_instance()) merged_fields = deepcopy(self._translation_form.fields) merged_fields.update(self.fields) self.fields = merged_fields
def __init__(self, obj): self.obj = obj self.fields = deepcopy(self.base_fields)
def __deepcopy__(self, memo): return deepcopy(self.fndef, memo)
def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj
def __deepcopy__(self, memo): obj = super(PrimitiveListWidget, self).__deepcopy__(memo) obj.subfield = copy.deepcopy(self.subfield) return obj
def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) return result
def __deepcopy__(self, memo): return self.__class__([(key, deepcopy(value, memo)) for key, value in self.iteritems()])
def __deepcopy__(self, memo): # Changed to use deepcopy from copycompat, instead of copy # For Python 2.4. from django.utils.copycompat import deepcopy return deepcopy(self._wrapped, memo)
def __deepcopy__(self, memo): obj = super(MultiWidget, self).__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj
def __deepcopy__(self, memo): obj = VectorLayerList() for thing in self: obj.append(copy.deepcopy(thing)) return obj
def __deepcopy__(self, memo): obj = super(Map, self).__deepcopy__(memo) obj.vector_layers = copy.deepcopy(self.vector_layers) return obj
def __new__(cls, name, bases, attrs): super_new = super(ModelBase, cls).__new__ parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: # If this isn't a subclass of Model, don't do anything special. return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop('__module__') new_class = super_new(cls, name, bases, {'__module__': module}) attr_meta = attrs.pop('Meta', None) abstract = getattr(attr_meta, 'abstract', False) if not attr_meta: meta = getattr(new_class, 'Meta', None) else: meta = attr_meta base_meta = getattr(new_class, '_meta', None) if getattr(meta, 'app_label', None) is None: # Figure out the app_label by looking one level up. # For 'django.contrib.sites.models', this would be 'sites'. model_module = sys.modules[new_class.__module__] kwargs = {"app_label": model_module.__name__.split('.')[-2]} else: kwargs = {} new_class.add_to_class('_meta', Options(meta, **kwargs)) if not abstract: new_class.add_to_class( 'DoesNotExist', subclass_exception( 'DoesNotExist', tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist, ), module)) new_class.add_to_class( 'MultipleObjectsReturned', subclass_exception( 'MultipleObjectsReturned', tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned, ), module)) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, 'ordering'): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, 'get_latest_by'): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy if getattr(new_class, '_default_manager', None): if not is_proxy: # Multi-table inheritance doesn't inherit default manager from # parents. new_class._default_manager = None new_class._base_manager = None else: # Proxy classes do inherit parent's default manager, if none is # set explicitly. new_class._default_manager = new_class._default_manager._copy_to_model( new_class) new_class._base_manager = new_class._base_manager._copy_to_model( new_class) # Bail out early if we have already created this class. m = get_model(new_class._meta.app_label, name, False) if m is not None: return m # Add all attributes to the class. for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = new_class._meta.local_fields + \ new_class._meta.local_many_to_many + \ new_class._meta.virtual_fields field_names = set([f.name for f in new_fields]) # Basic setup for proxy models. if is_proxy: base = None for parent in [cls for cls in parents if hasattr(cls, '_meta')]: if parent._meta.abstract: if parent._meta.fields: raise TypeError( "Abstract base class containing model fields not permitted for proxy model '%s'." % name) else: continue if base is not None: raise TypeError( "Proxy model '%s' has more than one non-abstract model base class." % name) else: base = parent if base is None: raise TypeError( "Proxy model '%s' has no non-abstract model base class." % name) if (new_class._meta.local_fields or new_class._meta.local_many_to_many): raise FieldError("Proxy model '%s' contains model fields." % name) while base._meta.proxy: base = base._meta.proxy_for_model new_class._meta.setup_proxy(base) # Do the appropriate setup for any model parents. o2o_map = dict([(f.rel.to, f) for f in new_class._meta.local_fields if isinstance(f, OneToOneField)]) for base in parents: original_base = base if not hasattr(base, '_meta'): # Things without _meta aren't functional models, so they're # uninteresting parents. continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many # Check for clashes between locally declared fields and those # on the base classes (we cannot handle shadowed fields at the # moment). for field in parent_fields: if field.name in field_names: raise FieldError('Local field %r in class %r clashes ' 'with field of similar name from ' 'base class %r' % (field.name, name, base.__name__)) if not base._meta.abstract: # Concrete classes... while base._meta.proxy: # Skip over a proxy class to the "real" base it proxies. base = base._meta.proxy_for_model if base in o2o_map: field = o2o_map[base] elif not is_proxy: attr_name = '%s_ptr' % base._meta.module_name field = OneToOneField(base, name=attr_name, auto_created=True, parent_link=True) new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: # .. and abstract ones. for field in parent_fields: new_class.add_to_class(field.name, copy.deepcopy(field)) # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base._meta.parents) # Inherit managers from the abstract base classes. new_class.copy_managers(base._meta.abstract_managers) # Proxy models inherit the non-abstract managers from their base, # unless they have redefined any of them. if is_proxy: new_class.copy_managers(original_base._meta.concrete_managers) # Inherit virtual fields (like GenericForeignKey) from the parent # class for field in base._meta.virtual_fields: if base._meta.abstract and field.name in field_names: raise FieldError('Local field %r in class %r clashes '\ 'with field of similar name from '\ 'abstract base class %r' % \ (field.name, name, base.__name__)) new_class.add_to_class(field.name, copy.deepcopy(field)) if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() register_models(new_class._meta.app_label, new_class) # Because of the way imports happen (recursively), we may or may not be # the first time this model tries to register with the framework. There # should only be one class for each model, so we always return the # registered version. return get_model(new_class._meta.app_label, name, False)
def _combine(self, other, conn): if not isinstance(other, Q): raise TypeError(other) obj = deepcopy(self) obj.add(other, conn) return obj
def subform(self, fieldset=()): form = deepcopy(self) form.fields = SortedDict([(key, self.fields[key]) for key in fieldset]) return form
def __init__(self): # route regex self._parse_route() # fields self.fields = deepcopy(self.base_fields)
def __new__(cls, name, bases, attrs): super_new = super(ModelBase, cls).__new__ parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: # If this isn't a subclass of Model, don't do anything special. return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop('__module__') new_class = super_new(cls, name, bases, {'__module__': module}) attr_meta = attrs.pop('Meta', None) abstract = getattr(attr_meta, 'abstract', False) if not attr_meta: meta = getattr(new_class, 'Meta', None) else: meta = attr_meta base_meta = getattr(new_class, '_meta', None) if getattr(meta, 'app_label', None) is None: # Figure out the app_label by looking one level up. # For 'django.contrib.sites.models', this would be 'sites'. model_module = sys.modules[new_class.__module__] kwargs = {"app_label": model_module.__name__.split('.')[-2]} else: kwargs = {} new_class.add_to_class('_meta', Options(meta, **kwargs)) if not abstract: new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist,), module)) new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned,), module)) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, 'ordering'): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, 'get_latest_by'): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy if getattr(new_class, '_default_manager', None): if not is_proxy: # Multi-table inheritance doesn't inherit default manager from # parents. new_class._default_manager = None new_class._base_manager = None else: # Proxy classes do inherit parent's default manager, if none is # set explicitly. new_class._default_manager = new_class._default_manager._copy_to_model(new_class) new_class._base_manager = new_class._base_manager._copy_to_model(new_class) # Bail out early if we have already created this class. m = get_model(new_class._meta.app_label, name, False) if m is not None: return m # Add all attributes to the class. for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = new_class._meta.local_fields + \ new_class._meta.local_many_to_many + \ new_class._meta.virtual_fields field_names = set([f.name for f in new_fields]) # Basic setup for proxy models. if is_proxy: base = None for parent in [cls for cls in parents if hasattr(cls, '_meta')]: if parent._meta.abstract: if parent._meta.fields: raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name) else: continue if base is not None: raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name) else: base = parent if base is None: raise TypeError("Proxy model '%s' has no non-abstract model base class." % name) if (new_class._meta.local_fields or new_class._meta.local_many_to_many): raise FieldError("Proxy model '%s' contains model fields." % name) while base._meta.proxy: base = base._meta.proxy_for_model new_class._meta.setup_proxy(base) # Do the appropriate setup for any model parents. o2o_map = dict([(f.rel.to, f) for f in new_class._meta.local_fields if isinstance(f, OneToOneField)]) for base in parents: original_base = base if not hasattr(base, '_meta'): # Things without _meta aren't functional models, so they're # uninteresting parents. continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many # Check for clashes between locally declared fields and those # on the base classes (we cannot handle shadowed fields at the # moment). for field in parent_fields: if field.name in field_names: raise FieldError('Local field %r in class %r clashes ' 'with field of similar name from ' 'base class %r' % (field.name, name, base.__name__)) if not base._meta.abstract: # Concrete classes... while base._meta.proxy: # Skip over a proxy class to the "real" base it proxies. base = base._meta.proxy_for_model if base in o2o_map: field = o2o_map[base] elif not is_proxy: attr_name = '%s_ptr' % base._meta.module_name field = OneToOneField(base, name=attr_name, auto_created=True, parent_link=True) new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: # .. and abstract ones. for field in parent_fields: new_class.add_to_class(field.name, copy.deepcopy(field)) # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base._meta.parents) # Inherit managers from the abstract base classes. new_class.copy_managers(base._meta.abstract_managers) # Proxy models inherit the non-abstract managers from their base, # unless they have redefined any of them. if is_proxy: new_class.copy_managers(original_base._meta.concrete_managers) # Inherit virtual fields (like GenericForeignKey) from the parent # class for field in base._meta.virtual_fields: if base._meta.abstract and field.name in field_names: raise FieldError('Local field %r in class %r clashes '\ 'with field of similar name from '\ 'abstract base class %r' % \ (field.name, name, base.__name__)) new_class.add_to_class(field.name, copy.deepcopy(field)) if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() register_models(new_class._meta.app_label, new_class) # Because of the way imports happen (recursively), we may or may not be # the first time this model tries to register with the framework. There # should only be one class for each model, so we always return the # registered version. return get_model(new_class._meta.app_label, name, False)
def __invert__(self): obj = deepcopy(self) obj.negate() return obj