Python django.db.models 模块,get_model() 实例源码

我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用django.db.models.get_model()

项目:djangosaml2    作者:knaperek    | 项目源码 | 文件源码
def get_model(model_path):
    try:
        from django.apps import apps
        return apps.get_model(model_path)
    except ImportError:
        # Django < 1.7 (cannot use the new app loader)
        from django.db.models import get_model as django_get_model
        try:
            app_label, model_name = model_path.split('.')
        except ValueError:
            raise ImproperlyConfigured("SAML_USER_MODEL must be of the form "
                "'app_label.model_name'")
        user_model = django_get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("SAML_USER_MODEL refers to model '%s' "
                "that has not been installed" % model_path)
        return user_model
项目:django-changeset    作者:beachmachine    | 项目源码 | 文件源码
def get_all_objects_created_by_user(user, object_type):
    """
    returns all objects of type "object-type" that have been created by user
    :param user: the user object
    :type: django.contrib.auth.models.User
    :param object_type: the content type object
    :type object_type: django.contrib.contenttypes.models.ContentType
    :return: a list with objects of type `object_type`
    :rtype: list of object_type
    """
    queryset = ChangeSet.objects.filter(user=user, object_type=object_type)

    # first, collect the primary keys (object_uuid) of all change_sets that look like a created object
    pks = []
    for change_set in queryset:
        # get earliest change record
        change_record = change_set.change_records.all().earliest()

        # was this created by the user?
        if change_record.change_set.user == user:
            # must not be related, old value must be none and new value must be not none
            if not change_record.is_related and change_record.old_value is None and change_record.new_value is not None:
                # only add if it has not been added
                if change_set.id not in pks:
                    pks.append(change_set.object_uuid)

    # get the class of this object_type / content_type
    obj_class = get_model(app_label=object_type.app_label, model_name=object_type.model)

    # and return all objects of that class with the given primary keys
    return obj_class.objects.filter(pk__in=pks)
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def _get_model_from_node(self, node, attr):
        """
        Helper to look up a model from a <object model=...> or a <field
        rel=... to=...> node.
        """
        model_identifier = node.getAttribute(attr)
        if not model_identifier:
            raise base.DeserializationError(
                "<%s> node is missing the required '%s' attribute" \
                    % (node.nodeName, attr))
        try:
            Model = models.get_model(*model_identifier.split("."))
        except TypeError:
            Model = None
        if Model is None:
            raise base.DeserializationError(
                "<%s> node has invalid model identifier: '%s'" % \
                    (node.nodeName, model_identifier))
        return Model
项目:penndjangosaml2    作者:wharton    | 项目源码 | 文件源码
def get_model(model_path):
    try:
        from django.apps import apps
        return apps.get_model(model_path)
    except ImportError:
        # Django < 1.7 (cannot use the new app loader)
        from django.db.models import get_model as django_get_model
        try:
            app_label, model_name = model_path.split('.')
        except ValueError:
            raise ImproperlyConfigured("SAML_USER_MODEL must be of the form "
                "'app_label.model_name'")
        user_model = django_get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("SAML_USER_MODEL refers to model '%s' "
                "that has not been installed" % model_path)
        return user_model
项目:mes    作者:osess    | 项目源码 | 文件源码
def context(self, context):
        btns = []
        for b in self.q_btns:
            btn = {}
            if 'model' in b:
                model = self.get_model(b['model'])
                if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.module_name)):
                    continue
                btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label,
                                                      model._meta.module_name, b.get('view', 'changelist')))
                btn['title'] = model._meta.verbose_name
                btn['icon'] = self.dashboard.get_model_icon(model)
            else:
                btn['url'] = b['url']

            if 'title' in b:
                btn['title'] = b['title']
            if 'icon' in b:
                btn['icon'] = b['icon']
            btns.append(btn)

        context.update({'btns': btns})
项目:mes    作者:osess    | 项目源码 | 文件源码
def get_notification_language(user):
    """
    Returns site-specific notification language for this user. Raises
    LanguageStoreNotAvailable if this site does not use translated
    notifications.
    """
    if getattr(settings, "NOTIFICATION_LANGUAGE_MODULE", False):
        try:
            app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split(".")
            model = models.get_model(app_label, model_name)
            language_model = model._default_manager.get(user__id__exact=user.id)
            if hasattr(language_model, "language"):
                return language_model.language
        except (ImportError, ImproperlyConfigured, model.DoesNotExist):
            raise LanguageStoreNotAvailable
    raise LanguageStoreNotAvailable
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def get_django_model(app_label, model_name):
        return models.get_model(app_label, model_name)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def get_django_model(app_label, model_name):
        return apps.get_model(app_label, model_name)
项目:Django-Web-Development-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def get_objects(parser, token):
    """
    Gets a queryset of objects of the model specified by app and model names

    Usage:

        {% get_objects [<manager>.]<method> from <app_name>.<model_name> [limit <amount>] as <var_name> %}

    Example:

        {% get_objects latest_published from people.Person limit 3 as people %}
        {% get_objects site_objects.all from articles.Article limit 3 as articles %}
        {% get_objects site_objects.all from articles.Article as articles %}

    """
    amount = None
    try:
        tag_name, manager_method, str_from, appmodel, str_limit, amount, str_as, var_name = token.split_contents()
    except ValueError:
        try:
            tag_name, manager_method, str_from, appmodel, str_as, var_name = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError, "get_objects tag requires a following syntax: {% get_objects <manager_method> from <app_name>.<model_name> limit <amount> as <var_name> %}"
    try:
        app_name, model_name = appmodel.split(".")
    except ValueError:
        raise template.TemplateSyntaxError, "get_objects tag requires application name and model name separated by a dot"
    model = models.get_model(app_name, model_name)
    return ObjectsNode(model, manager_method, amount, var_name)
项目:Django-Web-Development-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def get_objects(parser, token):
    """
    Gets a queryset of objects of the model specified by app and model names

    Usage:

        {% get_objects [<manager>.]<method> from <app_name>.<model_name> [limit <amount>] as <var_name> %}

    Example:

        {% get_objects latest_published from people.Person limit 3 as people %}
        {% get_objects site_objects.all from articles.Article limit 3 as articles %}
        {% get_objects site_objects.all from articles.Article as articles %}

    """
    amount = None
    try:
        tag_name, manager_method, str_from, appmodel, str_limit, amount, str_as, var_name = token.split_contents()
    except ValueError:
        try:
            tag_name, manager_method, str_from, appmodel, str_as, var_name = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError, "get_objects tag requires a following syntax: {% get_objects [<manager>.]<method> from <app_name>.<model_name> [limit <amount>] as <var_name> %}"
    try:
        app_name, model_name = appmodel.split(".")
    except ValueError:
        raise template.TemplateSyntaxError, "get_objects tag requires application name and model name separated by a dot"
    model = models.get_model(app_name, model_name)
    return ObjectsNode(model, manager_method, amount, var_name)
项目:beg-django-e-commerce    作者:Apress    | 项目源码 | 文件源码
def reference_class(self):
        if isinstance(self._reference_class, basestring):
            from django.db import models
            self._reference_class = models.get_model(
                *self._reference_class.split('.', 1))
        return self._reference_class
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def get_user_model():
        from . import app_settings
        from django.db.models import get_model

        try:
            app_label, model_name = app_settings.USER_MODEL.split('.')
        except ValueError:
            raise ImproperlyConfigured("AUTH_USER_MODEL must be of the"
                                       " form 'app_label.model_name'")
        user_model = get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("AUTH_USER_MODEL refers to model"
                                       " '%s' that has not been installed"
                                       % app_settings.USER_MODEL)
        return user_model
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def get_user_model():
    return django_apps.get_model(settings.DRIP_USER_MODEL)
项目:django-rest-framework-mongoengine-example    作者:BurkovBA    | 项目源码 | 文件源码
def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise auth.SiteProfileNotAvailable('You need to set AUTH_PROFILE_MO'
                                              'DULE in your project settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise auth.SiteProfileNotAvailable('app_label and model_name should'
                        ' be separated by a dot in the AUTH_PROFILE_MODULE set'
                        'ting')

            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise auth.SiteProfileNotAvailable('Unable to load the profile '
                        'model, check AUTH_PROFILE_MODULE in your project sett'
                        'ings')
                self._profile_cache = model._default_manager.using(self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise auth.SiteProfileNotAvailable
        return self._profile_cache
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def get_subject(self):
        """
        Returns the subject of a given event/alert.

        Sometimes, the subject is just a Netbox objects. Other times, it may
        be some physical or logical subcomponents of a Netbox.

        """
        if self.subid:
            subid = self.subid
            if self.event_type_id in self.SUBID_MAP:
                model = models.get_model('models',
                                         self.SUBID_MAP[self.event_type_id])
            elif (self.event_type_id == 'maintenanceState'
                  and 'service' in self.varmap.get(EventQueue.STATE_START, {})):
                model = models.get_model('models', 'Service')
            elif self.event_type_id == 'thresholdState':
                return ThresholdEvent(self)
            else:
                return UnknownEventSubject(self)

            if model:
                try:
                    return model.objects.get(pk=subid)
                except model.DoesNotExist:
                    _logger.warning("alert subid %s points to non-existant %s",
                                    subid, model)
                    return UnknownEventSubject(self)

        # catch-all
        return self.netbox or u"N/A"
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def __init__(self, event):
        self.event = event
        ruleid, self.metric = event.subid.split(':', 1)
        klass = models.get_model('models', 'ThresholdRule')
        try:
            self.rule = klass.objects.get(pk=ruleid)
        except klass.DoesNotExist:
            self.rule = None

        from nav.metrics.lookup import lookup
        self.subject = lookup(self.metric)
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def _get_model(model_identifier):
    """
    Helper to look up a model from an "app_label.model_name" string.
    """
    try:
        Model = models.get_model(*model_identifier.split("."))
    except TypeError:
        Model = None
    if Model is None:
        raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
    return Model
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        warnings.warn("The use of AUTH_PROFILE_MODULE to define user profiles has been deprecated.",
            DeprecationWarning, stacklevel=2)
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable(
                    'You need to set AUTH_PROFILE_MODULE in your project '
                    'settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable(
                    'app_label and model_name should be separated by a dot in '
                    'the AUTH_PROFILE_MODULE setting')
            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise SiteProfileNotAvailable(
                        'Unable to load the profile model, check '
                        'AUTH_PROFILE_MODULE in your project settings')
                self._profile_cache = model._default_manager.using(
                                   self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def get_user_model():
    """
    Returns the User model that is active in this project.
    """
    from django.db.models import get_model

    try:
        app_label, model_name = settings.AUTH_USER_MODEL.split('.')
    except ValueError:
        raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
    user_model = get_model(app_label, model_name)
    if user_model is None:
        raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
    return user_model
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def model_class(self):
        "Returns the Python model class for this type of content."
        return models.get_model(self.app_label, self.model,
                                only_installed=False)
项目:mes    作者:osess    | 项目源码 | 文件源码
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)
项目:mes    作者:osess    | 项目源码 | 文件源码
def get_model(self, model_or_label):
        if isinstance(model_or_label, ModelBase):
            return model_or_label
        else:
            return models.get_model(*model_or_label.lower().split('.'))
项目:mes    作者:osess    | 项目源码 | 文件源码
def get_models():
    """
    Returns a lookup of 'app_label.model': <model class> from ACTSTREAM_SETTINGS['MODELS']
    Only call this right before you need to inspect the models
    """
    models = {}
    for model in SETTINGS.get('MODELS', ('auth.User',)):
        models[model.lower()] = get_model(*model.split('.'))
    return models
项目:partytime    作者:sunlightlabs    | 项目源码 | 文件源码
def search(self, request):

        #   Searches in the fields of the given related model and returns the 
        #   result as a simple string to be used by the jQuery Autocomplete plugin

        query = request.GET.get('q', None) 

        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)

        #print '-----------------------'
        #print search_fields, app_label, model_name, query

        if search_fields and app_label and model_name and query:
            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    return "%s__istartswith" % field_name[1:]
                elif field_name.startswith('='):
                    return "%s__iexact" % field_name[1:]
                elif field_name.startswith('@'):
                    return "%s__search" % field_name[1:]
                else:
                    return "%s__icontains" % field_name

            model = models.get_model(app_label, model_name)
            q = None
            for field_name in search_fields.split(','):
                name = construct_search(field_name)
                #print name,'=',query
                if q:
                    q = q | models.Q( **{str(name):query} )
                else:
                    q = models.Q( **{str(name):query} )
            qs = model.objects.filter( q )

            data = ''.join([u'%s|%s\n' % (f, f.pk) for f in qs])
            return HttpResponse(data)
        return HttpResponseNotFound()
项目:partytime    作者:sunlightlabs    | 项目源码 | 文件源码
def search(self, request):

        #   Searches in the fields of the given related model and returns the 
        #   result as a simple string to be used by the jQuery Autocomplete plugin

        query = request.GET.get('q', None) 

        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)

        #print '-----------------------'
        #print search_fields, app_label, model_name, query

        if search_fields and app_label and model_name and query:
            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    return "%s__istartswith" % field_name[1:]
                elif field_name.startswith('='):
                    return "%s__iexact" % field_name[1:]
                elif field_name.startswith('@'):
                    return "%s__search" % field_name[1:]
                else:
                    return "%s__icontains" % field_name

            model = models.get_model(app_label, model_name)
            q = None
            for field_name in search_fields.split(','):
                name = construct_search(field_name)
                #print name,'=',query
                if q:
                    q = q | models.Q( **{str(name):query} )
                else:
                    q = models.Q( **{str(name):query} )
            qs = model.objects.filter( q )

            data = ''.join([u'%s|%s\n' % (f, f.pk) for f in qs])
            return HttpResponse(data)
        return HttpResponseNotFound()
项目:social-app-django    作者:python-social-auth    | 项目源码 | 文件源码
def get_rel_model(field):
    if django.VERSION >= (2, 0):
        return field.remote_field.model

    user_model = field.rel.to
    if isinstance(user_model, six.string_types):
        app_label, model_name = user_model.split('.')
        user_model = models.get_model(app_label, model_name)
    return user_model
项目:Provo-Housing-Database    作者:marcopete5    | 项目源码 | 文件源码
def get_user_model():
        from . import app_settings
        from django.db.models import get_model

        try:
            app_label, model_name = app_settings.USER_MODEL.split('.')
        except ValueError:
            raise ImproperlyConfigured("AUTH_USER_MODEL must be of the"
                                       " form 'app_label.model_name'")
        user_model = get_model(app_label, model_name)
        if user_model is None:
            raise ImproperlyConfigured("AUTH_USER_MODEL refers to model"
                                       " '%s' that has not been installed"
                                       % app_settings.USER_MODEL)
        return user_model
项目:django-boardinghouse    作者:schinckel    | 项目源码 | 文件源码
def test_run_python(self):
        """
        Because this can run arbitrary python code, we can't know
        which parts of it need to run against each schema, and which
        parts run against the public schema.

        We could hack into any generated SQL, and inspect it, looking
        for table names, attempting to push data to the correct
        schemata (including executing the SQL multiple times if
        necessary).

        Maybe we could fuck with the models generated by project_state.render(),
        and make their generated SQL do what we need it to do. Although, it looks
        like Pony.objects is a normal models.Manager class.
        """
        project_state = self.set_up_test_model()

        def forwards(models, schema_editor):
            Pony = models.get_model('tests', 'Pony')
            Pony.objects.create(pink=1, weight=3.55)
            Pony.objects.create(weight=5)

        def backwards(models, schema_editor):
            Pony = models.get_model('tests', 'Pony')
            Pony.objects.filter(pink=1, weight=3.55).delete()
            Pony.objects.filter(weight=5).delete()

        operation = migrations.RunPython(forwards, reverse_code=backwards)
        new_state = project_state.clone()
        operation.state_forwards('tests', new_state)

        Pony = project_state.apps.get_model('tests', 'Pony')

        @all_schemata
        def pony_count(count, **kwargs):
            found = Pony.objects.count()
            self.assertEqual(
                count,
                found,
                'Incorrect number of Ponies found in schema '
                '{schema}: expected {0}, found {1}'.format(count, found, **kwargs)
            )

        pony_count(0)

        with connection.schema_editor() as editor:
            operation.database_forwards('tests', editor, project_state, new_state)

        pony_count(2)

        with connection.schema_editor() as editor:
            operation.database_backwards('tests', editor, new_state, project_state)

        pony_count(0)
项目:mes    作者:osess    | 项目源码 | 文件源码
def handle(self, *app_labels, **options):

        # Activate project's default language
        translation.activate(settings.LANGUAGE_CODE)

        comment = options["comment"]
        batch_size = options["batch_size"]

        verbosity = int(options.get("verbosity", 1))
        app_list = SortedDict()
        # if no apps given, use all installed.
        if len(app_labels) == 0:
            for app in models.get_apps ():
                if not app in app_list:
                    app_list[app] = []
                for model_class in models.get_models(app):
                    if not model_class in app_list[app]:
                        app_list[app].append(model_class)
        else:
            for label in app_labels:
                try:
                    app_label, model_label = label.split(".")
                    try:
                        app = models.get_app(app_label)
                    except ImproperlyConfigured:
                        raise CommandError("Unknown application: %s" % app_label)

                    model_class = models.get_model(app_label, model_label)
                    if model_class is None:
                        raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
                    if app in app_list:
                        if app_list[app] and model_class not in app_list[app]:
                            app_list[app].append(model_class)
                    else:
                        app_list[app] = [model_class]
                except ValueError:
                    # This is just an app - no model qualifier.
                    app_label = label
                    try:
                        app = models.get_app(app_label)
                        if not app in app_list:
                            app_list[app] = []
                        for model_class in models.get_models(app):
                            if not model_class in app_list[app]:
                                app_list[app].append(model_class)
                    except ImproperlyConfigured:
                        raise CommandError("Unknown application: %s" % app_label)
        # Create revisions.
        for app, model_classes in app_list.items():
            for model_class in model_classes:
                self.create_initial_revisions(app, model_class, comment, batch_size, verbosity)

        # Go back to default language
        translation.deactivate()
项目:partytime    作者:sunlightlabs    | 项目源码 | 文件源码
def search(self, request):

        #    Searches in the fields of the given related model and returns the 
        #    result as a simple string to be used by the jQuery Autocomplete plugin

        query = request.GET.get('q', None)  # ?? ?????? ?????? ??? ????????? ?????????!!!

        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)

        #print '-----------------------'
        #print search_fields, app_label, model_name, query

        if search_fields and app_label and model_name and query:
            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    return "%s__istartswith" % field_name[1:]
                elif field_name.startswith('='):
                    return "%s__iexact" % field_name[1:]
                elif field_name.startswith('@'):
                    return "%s__search" % field_name[1:]
                else:
                    return "%s__icontains" % field_name

            model = models.get_model(app_label, model_name)
            q = None
            for field_name in search_fields.split(','):
                name = construct_search(field_name)
                #print name,'=',query
                if q:
                    q = q | models.Q( **{str(name):query} )
                else:
                    q = models.Q( **{str(name):query} )
            qs = model.objects.filter( q )

            rel_name = field_name.split('__')[0]            

            data = ''.join([u'%s|%s\n' % (getattr(f,rel_name), f.pk) for f in qs])
#            data = ''.join([u'%s|%s\n' % (f.__unicode__(), f.pk) for f in qs])
            return HttpResponse(data)
        return HttpResponseNotFound()