Python django.db.models.base.ModelBase() Examples

The following are 30 code examples of django.db.models.base.ModelBase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.base , or try the search function .
Example #1
Source File: admin.py    From django-ra-erp with GNU Affero General Public License v3.0 7 votes vote down vote up
def get_permission_override_model(self, request, **kwargs):
        """
        Return a string reprsentation of the model to look into its permissions,
        :param request:
        :param kwargs:
        :return:
        """
        if self.permission_override_model is True:
            return self.parent_model._meta.model_name

        elif type(self.permission_override_model) is str:
            return self.permission_override_model

        elif type(self.permission_override_model) is ModelBase:
            return self.permission_override_model._meta.model_name

        else:
            raise ImproperlyConfigured(
                'self.permission_override_model can be True, False , str or ModelBase .Got %s instead ' % type(
                    self.permission_override_model)) 
Example #2
Source File: fields.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def _check_generic_foreign_key_existence(self):
        target = self.remote_field.model
        if isinstance(target, ModelBase):
            fields = target._meta.virtual_fields
            if any(isinstance(field, GenericForeignKey) and
                    field.ct_field == self.content_type_field_name and
                    field.fk_field == self.object_id_field_name
                    for field in fields):
                return []
            else:
                return [
                    checks.Error(
                        ("The GenericRelation defines a relation with the model "
                         "'%s.%s', but that model does not have a GenericForeignKey.") % (
                            target._meta.app_label, target._meta.object_name
                        ),
                        hint=None,
                        obj=self,
                        id='contenttypes.E004',
                    )
                ]
        else:
            return [] 
Example #3
Source File: shortcuts.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def _get_queryset(klass):
    """
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
    get_object_or_404 and get_list_or_404 more DRY.

    Raises a ValueError if klass is not a Model, Manager, or QuerySet.
    """
    if isinstance(klass, QuerySet):
        return klass
    elif isinstance(klass, Manager):
        manager = klass
    elif isinstance(klass, ModelBase):
        manager = klass._default_manager
    else:
        if isinstance(klass, type):
            klass__name = klass.__name__
        else:
            klass__name = klass.__class__.__name__
        raise ValueError("Object is of type '%s', but must be a Django Model, "
                         "Manager, or QuerySet" % klass__name)
    return manager.all() 
Example #4
Source File: models.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def approx_count(db_table_of_model):
    """
    Return approx db table total record count.
    Good enough if you don’t need the exact count.
    This value is updated by both autovacuum and autoanalyze,
    so it should never be much more than 10% off.
    :param db_table_of_model: str OR Model class
    :return: int
    """
    if isinstance(db_table_of_model, ModelBase):
        db_table = db_table_of_model._meta.db_table
    elif isinstance(db_table_of_model, str):
        db_table = db_table_of_model
    else:
        raise ValueError('Provide either str table name ot Model class.')
    with connection.cursor() as cursor:
        cursor.execute(
            f"SELECT reltuples::bigint FROM pg_catalog.pg_class WHERE relname = '{db_table}';")
        return cursor.fetchone()[0] 
Example #5
Source File: test_mixins.py    From Disfactory with MIT License 6 votes vote down vote up
def setUp(self):
        # Create a dummy model which extends the mixin. A RuntimeWarning will
        # occur if the model is registered twice
        if not hasattr(self, 'model'):
            self.model = ModelBase(
                '__TestModel__' +
                self.mixin.__name__, (self.mixin,),
                {'__module__': self.mixin.__module__}
            )

        # Create the schema for our test model. If the table already exists,
        # will pass
        try:
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(self.model)
            super(AbstractModelMixinTestCase, self).setUpClass()
        except ProgrammingError:
            pass 
Example #6
Source File: models.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def __new__(cls, name, bases, dct):
        def getMeta(k, default=None):
            try:
                return getattr(dct['Meta'], k)
            except KeyError:
                return default
            except AttributeError:
                return default

        is_script_model = dct.get('__module__', '__main__') == '__main__'
        if not getMeta('abstract'):
            dct['__module__'] = 'standalone.models'
        newClass = base.ModelBase.__new__(cls, name, bases, dct)
        if is_script_model or dct.get('force_install_standalone_models', False):
            mod = import_module('standalone.models')
            setattr(mod, name, newClass)
        return newClass 
Example #7
Source File: admin.py    From django-restful-admin with MIT License 6 votes vote down vote up
def register(self, model_or_iterable, view_class=None, **options):
        if not view_class:
            view_class = self.default_view_class

        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model._meta.abstract:
                raise ImproperlyConfigured(
                    'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
                )

            if model in self._registry:
                raise AlreadyRegistered('The model %s is already registered' % model.__name__)
            options.update({
                "__doc__": self.generate_docs(model)
            })
            view_class = type("%sAdmin" % model.__name__, (view_class,), options)
            # self.set_docs(view_class, model)
            # Instantiate the admin class to save in the registry
            self._registry[model] = view_class 
Example #8
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def _get_queryset(klass):
    """
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
    get_object_or_404 and get_list_or_404 more DRY.

    Raises a ValueError if klass is not a Model, Manager, or QuerySet.
    """
    if isinstance(klass, QuerySet):
        return klass
    elif isinstance(klass, Manager):
        manager = klass
    elif isinstance(klass, ModelBase):
        manager = klass._default_manager
    else:
        klass__name = klass.__name__ if isinstance(klass, type) \
                      else klass.__class__.__name__
        raise ValueError("Object is of type '%s', but must be a Django Model, "
                         "Manager, or QuerySet" % klass__name)
    return manager.all() 
Example #9
Source File: dashboard.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_model(self, model_or_label):
        if isinstance(model_or_label, ModelBase):
            return model_or_label
        else:
            return apps.get_model(*model_or_label.lower().split('.')) 
Example #10
Source File: sites.py    From python2017 with MIT License 5 votes vote down vote up
def unregister(self, model_or_iterable):
        """
        Unregisters the given model(s).

        If a model isn't already registered, this will raise NotRegistered.
        """
        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model not in self._registry:
                raise NotRegistered('The model %s is not registered' % model.__name__)
            del self._registry[model] 
Example #11
Source File: models.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_unicode(o) 
Example #12
Source File: dashboard.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def prepare_value(self, value):
        if isinstance(value, ModelBase):
            value = '%s.%s' % (value._meta.app_label, value._meta.model_name)
        return value 
Example #13
Source File: models.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example #14
Source File: dashboard.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_model(self, model_or_label):
        if isinstance(model_or_label, ModelBase):
            return model_or_label
        else:
            return apps.get_model(*model_or_label.lower().split('.')) 
Example #15
Source File: dashboard.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def prepare_value(self, value):
        if isinstance(value, ModelBase):
            value = '%s.%s' % (value._meta.app_label, value._meta.model_name)
        return value 
Example #16
Source File: dashboard.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, ModelBase):
            return value
        app_label, model_name = value.lower().split('.')
        return apps.get_model(app_label, model_name) 
Example #17
Source File: sites.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def register(self, model_or_iterable, admin_class=object, **options):
        from xadmin.views.base import BaseAdminView
        if isinstance(model_or_iterable, ModelBase) or issubclass(model_or_iterable, BaseAdminView):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if isinstance(model, ModelBase):
                if model._meta.abstract:
                    raise ImproperlyConfigured('The model %s is abstract, so it '
                                               'cannot be registered with admin.' % model.__name__)

                if model in self._registry:
                    raise AlreadyRegistered(
                        'The model %s is already registered' % model.__name__)

                # If we got **options then dynamically construct a subclass of
                # admin_class with those **options.
                if options:
                    # For reasons I don't quite understand, without a __module__
                    # the created class appears to "live" in the wrong place,
                    # which causes issues later on.
                    options['__module__'] = __name__

                admin_class = type(str("%s%sAdmin" % (model._meta.app_label, model._meta.model_name)), (admin_class,), options or {})
                admin_class.model = model
                admin_class.order = self.model_admins_order
                self.model_admins_order += 1
                self._registry[model] = admin_class
            else:
                if model in self._registry_avs:
                    raise AlreadyRegistered('The admin_view_class %s is already registered' % model.__name__)
                if options:
                    options['__module__'] = __name__
                    admin_class = type(str(
                        "%sAdmin" % model.__name__), (admin_class,), options)

                # Instantiate the admin class to save in the registry
                self._registry_avs[model] = admin_class 
Example #18
Source File: models.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example #19
Source File: sites.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def register(self, model_or_iterable, admin_class=object, **options):
        from xadmin.views.base import BaseAdminView
        if isinstance(model_or_iterable, ModelBase) or issubclass(model_or_iterable, BaseAdminView):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if isinstance(model, ModelBase):
                if model._meta.abstract:
                    raise ImproperlyConfigured('The model %s is abstract, so it '
                                               'cannot be registered with admin.' % model.__name__)

                if model in self._registry:
                    raise AlreadyRegistered(
                        'The model %s is already registered' % model.__name__)

                # If we got **options then dynamically construct a subclass of
                # admin_class with those **options.
                if options:
                    # For reasons I don't quite understand, without a __module__
                    # the created class appears to "live" in the wrong place,
                    # which causes issues later on.
                    options['__module__'] = __name__

                admin_class = type(str("%s%sAdmin" % (model._meta.app_label, model._meta.model_name)), (admin_class,), options or {})
                admin_class.model = model
                admin_class.order = self.model_admins_order
                self.model_admins_order += 1
                self._registry[model] = admin_class
            else:
                if model in self._registry_avs:
                    raise AlreadyRegistered('The admin_view_class %s is already registered' % model.__name__)
                if options:
                    options['__module__'] = __name__
                    admin_class = type(str(
                        "%sAdmin" % model.__name__), (admin_class,), options)

                # Instantiate the admin class to save in the registry
                self._registry_avs[model] = admin_class 
Example #20
Source File: dashboard.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def get_model(self, model_or_label):
        if isinstance(model_or_label, ModelBase):
            return model_or_label
        else:
            return apps.get_model(*model_or_label.lower().split('.')) 
Example #21
Source File: dashboard.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def prepare_value(self, value):
        if isinstance(value, ModelBase):
            value = '%s.%s' % (value._meta.app_label, value._meta.model_name)
        return value 
Example #22
Source File: dashboard.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, ModelBase):
            return value
        app_label, model_name = value.lower().split('.')
        return apps.get_model(app_label, model_name) 
Example #23
Source File: dashboard.py    From devops with MIT License 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, ModelBase):
            return value
        app_label, model_name = value.lower().split('.')
        return models.get_model(app_label, model_name) 
Example #24
Source File: sites.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def register(self, model_or_iterable, admin_class=object, **options):
        from xadmin.views.base import BaseAdminView
        if isinstance(model_or_iterable, ModelBase) or issubclass(model_or_iterable, BaseAdminView):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if isinstance(model, ModelBase):
                if model._meta.abstract:
                    raise ImproperlyConfigured('The model %s is abstract, so it '
                                               'cannot be registered with admin.' % model.__name__)

                if model in self._registry:
                    raise AlreadyRegistered(
                        'The model %s is already registered' % model.__name__)

                # If we got **options then dynamically construct a subclass of
                # admin_class with those **options.
                if options:
                    # For reasons I don't quite understand, without a __module__
                    # the created class appears to "live" in the wrong place,
                    # which causes issues later on.
                    options['__module__'] = __name__

                admin_class = type(str("%s%sAdmin" % (model._meta.app_label, model._meta.model_name)), (admin_class,), options or {})
                admin_class.model = model
                admin_class.order = self.model_admins_order
                self.model_admins_order += 1
                self._registry[model] = admin_class
            else:
                if model in self._registry_avs:
                    raise AlreadyRegistered('The admin_view_class %s is already registered' % model.__name__)
                if options:
                    options['__module__'] = __name__
                    admin_class = type(str(
                        "%sAdmin" % model.__name__), (admin_class,), options)

                # Instantiate the admin class to save in the registry
                self._registry_avs[model] = admin_class 
Example #25
Source File: models.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example #26
Source File: dashboard.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def get_model(self, model_or_label):
        if isinstance(model_or_label, ModelBase):
            return model_or_label
        else:
            return apps.get_model(*model_or_label.lower().split('.')) 
Example #27
Source File: dashboard.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def prepare_value(self, value):
        if isinstance(value, ModelBase):
            value = '%s.%s' % (value._meta.app_label, value._meta.model_name)
        return value 
Example #28
Source File: dashboard.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, ModelBase):
            return value
        app_label, model_name = value.lower().split('.')
        return apps.get_model(app_label, model_name) 
Example #29
Source File: sites.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def unregister(self, model_or_iterable):
        """
        Unregisters the given model(s).

        If a model isn't already registered, this will raise NotRegistered.
        """
        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model not in self._registry:
                raise NotRegistered('The model %s is not registered' % model.__name__)
            del self._registry[model] 
Example #30
Source File: sites.py    From python with Apache License 2.0 5 votes vote down vote up
def unregister(self, model_or_iterable):
        """
        Unregisters the given model(s).

        If a model isn't already registered, this will raise NotRegistered.
        """
        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model not in self._registry:
                raise NotRegistered('The model %s is not registered' % model.__name__)
            del self._registry[model]