Python django.db.models.loading.get_model() Examples

The following are 29 code examples of django.db.models.loading.get_model(). 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.loading , or try the search function .
Example #1
Source File: models.py    From django-connections with MIT License 6 votes vote down vote up
def get_model(model):
    """
    Given a model name as ``app_label.ModelName``, returns the Django model.
    """
    try:
        if isinstance(model, str):
            app_label, model_name = model.split('.', 1)
            m = loading.get_model(app_label, model_name)
            if not m:  # pragma: no cover
                raise LookupError()  # Django < 1.7 just returns None
            return m
        elif issubclass(model, models.Model):
            return model
    except (LookupError, ValueError):
        pass
    raise ValueError(model) 
Example #2
Source File: models.py    From django-connections with MIT License 6 votes vote down vote up
def define_relationship(name, from_model, to_model):
    if name in _relationship_registry:
        raise KeyError(name)
    
    _from_ctype = from_model
    _to_ctype = to_model
    
    if isinstance(_from_ctype, str):
        _from_ctype = get_model(_from_ctype)
    if isinstance(_to_ctype, str):
        _to_ctype = get_model(_to_ctype)
    
    if not isinstance(_from_ctype, ContentType):
        _from_ctype = ContentType.objects.get_for_model(_from_ctype)
    if not isinstance(_to_ctype, ContentType):
        _to_ctype = ContentType.objects.get_for_model(_to_ctype)
    
    relationship = Relationship(name=name,
                                from_content_type=_from_ctype,
                                to_content_type=_to_ctype)
    
    _relationship_registry[name] = relationship
    return relationship 
Example #3
Source File: shortcuts.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_usersettings_model():
    """
    Returns the ``UserSettings`` model that is active in this project.
    """
    try:
        from django.apps import apps
        get_model = apps.get_model
    except ImportError:
        from django.db.models.loading import get_model

    try:
        app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
    except ValueError:
        raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the '
                                   'form "app_label.model_name"')
    usersettings_model = get_model(app_label, model_name)
    if usersettings_model is None:
        raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has '
                                   'not been installed' % settings.USERSETTINGS_MODEL)
    return usersettings_model 
Example #4
Source File: views.py    From opensurfaces with MIT License 6 votes vote down vote up
def bsdf_wd_voted_no(request, template='endless_list.html',
                     extra_context=None):

    v = 'wd'
    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    entries = bsdf_model.objects \
        .filter(admin_score__lt=0) \
        .order_by('admin_score', '-shape__pixel_area', '-shape__correct_score')

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v,
        'subnav': 'voted-no',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_wd_thumb_vote.html',
        'v': v,
        'enable_voting': True,
    }, extra_context)

    return render(request, template, context) 
Example #5
Source File: models.py    From wagtail-embedvideos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_embed_video_model():
    try:
        app_label, model_name =\
            settings.WAGTAILEMBEDVIDEO_VIDEO_MODEL.split('.')
    except AttributeError:
        return EmbedVideo
    except ValueError:
        raise ImproperlyConfigured(
            "WAGTAILEMBEDVIDEO_VIDEO_MODEL must be of the form \
            'app_label.model_name'")

    embed_video_model = get_model(app_label, model_name)
    if embed_video_model is None:
        raise ImproperlyConfigured(
            "WAGTAILEMBEDVIDEO_VIDEO_MODEL refers to model '%s' that has not \
            been installed" % settings.WAGTAILEMBEDVIDEO_VIDE_MODEL)
    return embed_video_model 
Example #6
Source File: widgets.py    From django-searchable-select with GNU General Public License v2.0 6 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None, choices=()):
        if value is None:
            value = []

        if not isinstance(value, (list, tuple)):
            # This is a ForeignKey field. We must allow only one item.
            value = [value]

        values = get_model(self.model).objects.filter(pk__in=value)
        try:
            final_attrs = self.build_attrs(attrs, name=name)
        except TypeError as e:
            # Fallback for django 1.10+
            final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})

        return render_to_string('searchableselect/select.html', dict(
            field_id=final_attrs['id'],
            field_name=final_attrs['name'],
            values=values,
            model=self.model,
            search_field=self.search_field,
            limit=self.limit,
            many=self.many
        )) 
Example #7
Source File: views.py    From django-searchable-select with GNU General Public License v2.0 6 votes vote down vote up
def filter_models(request):
    model_name = request.GET.get('model')
    search_field = request.GET.get('search_field')
    value = request.GET.get('q')
    limit = int(request.GET.get('limit', 10))
    try:
        model = get_model(model_name)
    except LookupError as e:  # pragma: no cover
        return JsonResponse(dict(status=400, error=e.message))
    except (ValueError, AttributeError) as e:  # pragma: no cover
        return JsonResponse(dict(status=400, error='Malformed model parameter.'))

    values = model.objects.filter(**{'{}__icontains'.format(search_field): value})[:limit]
    values = [
        dict(pk=v.pk, name=smart_str(v))
        for v
        in values
    ]

    return JsonResponse(dict(result=values)) 
Example #8
Source File: views.py    From opensurfaces with MIT License 6 votes vote down vote up
def bsdf_wd_voted_yes(request, template='endless_list.html',
                      extra_context=None):

    v = 'wd'
    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    entries = bsdf_model.objects \
        .filter(admin_score__gt=0) \
        .order_by('-admin_score', '-shape__pixel_area', '-shape__correct_score')

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v,
        'subnav': 'voted-yes',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_wd_thumb_vote.html',
        'v': v,
        'enable_voting': True,
    }, extra_context)

    return render(request, template, context) 
Example #9
Source File: views.py    From opensurfaces with MIT License 6 votes vote down vote up
def bsdfs_csv(v, bsdfs):
    """ Return a list of BSDFs formatted as a tab-separated-value file """
    if v not in BSDF_VERSIONS:
        raise Http404

    response = HttpResponse(mimetype='text/csv')
    #response['Content-Disposition'] = 'attachment; filename="bsdfs.csv"'
    writer = csv.writer(response)

    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    fields = [f.name for f in bsdf_model._meta.fields]
    writer.writerow(fields)

    for bsdf in bsdfs:
        row = []
        for name in fields:
            value = getattr(bsdf, name)
            if hasattr(value, 'isoformat'):
                row.append(value.isoformat())
            else:
                row.append(value)
        writer.writerow(row)

    return response 
Example #10
Source File: views.py    From opensurfaces with MIT License 6 votes vote down vote up
def bsdf_all(request, v, template='endless_list.html', extra_context=None):
    if v not in BSDF_VERSIONS:
        raise Http404

    entries = get_model('bsdfs', 'ShapeBsdfLabel_' + v).objects.all() \
        .filter(time_ms__isnull=False,
                shape__photo__synthetic=False,
                shape__photo__inappropriate=False) \
        .order_by('-id')

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v, 'subnav': 'all',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_%s_shape_thumb.html' % v,
        'header': 'All submissions',
        'header_small': 'sorted by date',
        'v': v,
        #'enable_voting': False,
    }, extra_context)

    return render(request, template, context) 
Example #11
Source File: views.py    From opensurfaces with MIT License 6 votes vote down vote up
def bsdf_wd_voted_none(request, template='endless_list.html',
                       extra_context=None):

    v = 'wd'
    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    entries = bsdf_model.objects \
        .filter(give_up=False, admin_score=0, time_ms__gt=500) \
        .order_by('-shape__synthetic', '-shape__pixel_area')  # '-shape__pixel_area', '-shape__correct_score')

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v,
        'subnav': 'vote',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_wd_thumb_vote.html',
        'v': v,
        'enable_voting': True,
    }, extra_context)

    return render(request, template, context) 
Example #12
Source File: models.py    From opensurfaces with MIT License 5 votes vote down vote up
def material_shape_count(self):
        return get_model('shapes', 'MaterialShape').objects.filter(
            pixel_area__gt=Shape.MIN_PIXEL_AREA, correct=True,
            substance=self,
        ).count() 
Example #13
Source File: bootstrap_pages.py    From rocket-league-replays with GNU General Public License v3.0 5 votes vote down vote up
def create_page(entry):
    print(f"Creating {entry['title']}")

    content_type = ContentType.objects.get_for_model(get_model(entry['content_type']))
    content_type.model_class().objects.create(
        page=Page.objects.create(
            title=entry['title'],
            slug=entry['slug'],
            content_type=content_type,
            parent=Page.objects.get_homepage() if Page.objects.exists() else None,
        ),
        **entry['content']
    ) 
Example #14
Source File: utils.py    From opensurfaces with MIT License 5 votes vote down vote up
def dump_model_csv_view(app_name, model_name):

    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = (
        'attachment; filename="%s-%s.csv"' % (app_name, model_name))
    writer = csv.writer(response)

    model = get_model(app_name, model_name)
    fields = [f[0].attname for f in model._meta.get_fields_with_model()]

    writer.writerow(fields)
    for obj in model.objects.all().order_by('pk'):
        writer.writerow([getattr(obj, f) for f in fields])

    return response 
Example #15
Source File: utils.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def resolve_model(class_path):
    """
    Resolves a class path to a Django model class
    :param class_path: a string model class path
    :return:
    """
    return get_model(*class_path.split('.', 1)) 
Example #16
Source File: general.py    From django-htk with MIT License 5 votes vote down vote up
def _get_model_fn():
    try:
        from django.apps import apps
        get_model = apps.get_model
    except:
        from django.db.models.loading import get_model
    return get_model 
Example #17
Source File: general.py    From django-htk with MIT License 5 votes vote down vote up
def resolve_model_dynamically(module_str):
    (module_name, attr_name,) = get_module_name_parts(module_str)
    if module_name and attr_name:
        get_model = _get_model_fn()
        model = get_model(module_name, attr_name)
    else:
        model = None
    return model 
Example #18
Source File: views.py    From django-generic-scaffold with MIT License 5 votes vote down vote up
def get_url_names(app=None, model=None, prefix=None):
    model_class = None
    if app and model:
        model_class = get_model(app, model)
    return CrudManager.get_url_names(prefix=prefix, model_class=model_class) 
Example #19
Source File: views.py    From django-business-logic with MIT License 5 votes vote down vote up
def get_reference_model(self):
        try:
            app_name, model_name = self.get_reference_model_name().split('.')
            model = get_model(app_name, model_name)
        except (ValueError, LookupError):
            raise exceptions.NotFound()

        return model 
Example #20
Source File: models.py    From opensurfaces with MIT License 5 votes vote down vote up
def material_shape_count(self):
        return get_model('shapes', 'MaterialShape').objects.filter(
            pixel_area__gt=Shape.MIN_PIXEL_AREA, correct=True,
            name=self,
        ).count() 
Example #21
Source File: views.py    From opensurfaces with MIT License 5 votes vote down vote up
def bsdf_wd_vote(request):
    v = 'wd'
    id = request.POST['id']
    score = request.POST['score']
    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    bsdf_model.objects.filter(id=id).update(admin_score=score)
    return json_success_response() 
Example #22
Source File: views.py    From opensurfaces with MIT License 5 votes vote down vote up
def bsdf_detail(request, v, pk):
    if v not in BSDF_VERSIONS:
        raise Http404

    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    bsdf = get_object_or_404(bsdf_model, pk=pk)

    ct = ContentType.objects.get_for_model(bsdf_model)
    votes = [
        prepare_votes_bar_impl(
            ShapeBsdfQuality.objects.filter(
                content_type=ct, object_id=pk,
                color_correct__isnull=False, invalid=False)
            .values_list('color_correct', flat=True),
            bsdf.color_correct_score,
            'Color correct'),
        prepare_votes_bar_impl(
            ShapeBsdfQuality.objects.filter(
                content_type=ct, object_id=pk,
                gloss_correct__isnull=False, invalid=False)
            .values_list('gloss_correct', flat=True),
            bsdf.gloss_correct_score,
            'Gloss correct'),
    ]

    data = {
        'nav': 'browse/bsdf-%s' % v,
        'bsdf': bsdf,
        'shape': bsdf.shape,
        'photo': bsdf.shape.photo,
        'votes': votes,
        'v': v
    }

    return render(request, 'bsdf_%s_detail.html' % v, data) 
Example #23
Source File: views.py    From opensurfaces with MIT License 5 votes vote down vote up
def bsdf_bad(request, v, template='endless_list.html', extra_context=None):
    if v not in BSDF_VERSIONS:
        raise Http404

    entries = get_model('bsdfs', 'ShapeBsdfLabel_' + v).objects \
        .filter(shape__photo__inappropriate=False, shape__photo__synthetic=False) \
        .exclude(color_correct=True) \
        .exclude(gloss_correct=True) \
        .extra(
            select={'correct_score':
                    'color_correct_score + gloss_correct_score'},
            order_by=('correct_score',)
        )
        #.filter(time_ms__isnull=False, admin_score__lt=0, shape__synthetic=False) \
        #.order_by('admin_score', '-shape__pixel_area')

    if 'publishable' in request.GET:
        entries = entries.filter(shape__photo__license__publishable=True)

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v, 'subnav': 'bad',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_%s_shape_thumb.html' % v,
        'header': 'Low quality submissions',
        'header_small': 'sorted by quality',
        'v': v,
        #'enable_voting': False,
    }, extra_context)

    return render(request, template, context) 
Example #24
Source File: views.py    From opensurfaces with MIT License 5 votes vote down vote up
def bsdf_good(request, v, template='endless_list.html', extra_context=None):
    if v not in BSDF_VERSIONS:
        raise Http404

    entries = get_model('bsdfs', 'ShapeBsdfLabel_' + v).objects.all() \
        .filter(color_correct=True, gloss_correct=True,
                shape__photo__synthetic=False,
                shape__photo__inappropriate=False,
                shape__bsdf_wd_id=F('id')) \

    if 'by-id' in request.GET:
        header_small = 'sorted by id'
        entries = entries.order_by('-id')
    else:
        header_small = 'sorted by quality'
        entries = entries.extra(
            select={'correct_score':
                    'color_correct_score + gloss_correct_score'},
            order_by=('-correct_score',)
        ) \

    if 'publishable' in request.GET:
        entries = entries.filter(shape__photo__license__publishable=True)

    context = dict_union({
        'nav': 'browse/bsdf-%s' % v, 'subnav': 'good',
        'entries': entries,
        'base_template': 'bsdf_base.html',
        'thumb_template': 'bsdf_%s_shape_thumb.html' % v,
        'header': 'High quality submissions',
        'header_small': header_small,
        'v': v,
        #'enable_voting': False,
    }, extra_context)

    return render(request, template, context) 
Example #25
Source File: views.py    From opensurfaces with MIT License 5 votes vote down vote up
def bsdf_all_csv(request, v):
    """ Return ``bsdfs_csv()`` for all BSDFS """
    if v not in BSDF_VERSIONS:
        raise Http404
    bsdf_model = get_model('bsdfs', 'ShapeBsdfLabel_' + v)
    return bsdfs_csv(v, bsdf_model.objects.all().order_by('id')) 
Example #26
Source File: utils.py    From django-tenants with MIT License 5 votes vote down vote up
def get_tenant_domain_model():
    return get_model(settings.TENANT_DOMAIN_MODEL) 
Example #27
Source File: utils.py    From django-tenants with MIT License 5 votes vote down vote up
def get_tenant_model():
    return get_model(settings.TENANT_MODEL) 
Example #28
Source File: enrich.py    From stream-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _inject_objects(self, activities, objects, fields):
        for activity, field in itertools.product(activities, fields):
            if not self.is_ref(activity, field):
                continue
            f_ct, f_id = activity[field].split(':')
            model = get_model(*f_ct.split('.'))
            f_id = model._meta.pk.to_python(f_id)

            instance = objects[f_ct].get(f_id)
            if instance is None:
                activity.track_not_enriched_field(field, activity[field])
            else:
                activity[field] = self.enrich_instance(instance) 
Example #29
Source File: enrich.py    From stream-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _fetch_objects(self, references):
        objects = defaultdict(list)
        for content_type, ids in references.items():
            model = get_model(*content_type.split('.'))
            ids = set(ids)
            instances = self.fetch_model_instances(model, ids)
            objects[content_type] = instances
        return objects