(cls, name, bases, attrs, **kwargs)
| 96 | """Metaclass for all models.""" |
| 97 | |
| 98 | def __new__(cls, name, bases, attrs, **kwargs): |
| 99 | super_new = super().__new__ |
| 100 | |
| 101 | # Also ensure initialization is only performed for subclasses of Model |
| 102 | # (excluding Model class itself). |
| 103 | parents = [b for b in bases if isinstance(b, ModelBase)] |
| 104 | if not parents: |
| 105 | return super_new(cls, name, bases, attrs) |
| 106 | |
| 107 | # Create the class. |
| 108 | module = attrs.pop("__module__") |
| 109 | new_attrs = {"__module__": module} |
| 110 | classcell = attrs.pop("__classcell__", None) |
| 111 | if classcell is not None: |
| 112 | new_attrs["__classcell__"] = classcell |
| 113 | attr_meta = attrs.pop("Meta", None) |
| 114 | # Pass all attrs without a (Django-specific) contribute_to_class() |
| 115 | # method to type.__new__() so that they're properly initialized |
| 116 | # (i.e. __set_name__()). |
| 117 | contributable_attrs = {} |
| 118 | for obj_name, obj in attrs.items(): |
| 119 | if _has_contribute_to_class(obj): |
| 120 | contributable_attrs[obj_name] = obj |
| 121 | else: |
| 122 | new_attrs[obj_name] = obj |
| 123 | new_class = super_new(cls, name, bases, new_attrs, **kwargs) |
| 124 | |
| 125 | abstract = getattr(attr_meta, "abstract", False) |
| 126 | meta = attr_meta or getattr(new_class, "Meta", None) |
| 127 | base_meta = getattr(new_class, "_meta", None) |
| 128 | |
| 129 | app_label = None |
| 130 | |
| 131 | # Look for an application configuration to attach the model to. |
| 132 | app_config = apps.get_containing_app_config(module) |
| 133 | |
| 134 | if getattr(meta, "app_label", None) is None: |
| 135 | if app_config is None: |
| 136 | if not abstract: |
| 137 | raise RuntimeError( |
| 138 | "Model class %s.%s doesn't declare an explicit " |
| 139 | "app_label and isn't in an application in " |
| 140 | "INSTALLED_APPS." % (module, name) |
| 141 | ) |
| 142 | |
| 143 | else: |
| 144 | app_label = app_config.label |
| 145 | |
| 146 | new_class.add_to_class("_meta", Options(meta, app_label)) |
| 147 | if not abstract: |
| 148 | new_class.add_to_class( |
| 149 | "DoesNotExist", |
| 150 | subclass_exception( |
| 151 | "DoesNotExist", |
| 152 | tuple( |
| 153 | x.DoesNotExist |
| 154 | for x in parents |
| 155 | if hasattr(x, "_meta") and not x._meta.abstract |
no test coverage detected