Python django.db.models.Model() Examples

The following are 30 code examples of django.db.models.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 , or try the search function .
Example #1
Source File: util.py    From StormOnline with Apache License 2.0 7 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example #2
Source File: test_fields.py    From django-osm-field with MIT License 6 votes vote down vote up
def test_missing_fields(self):
        class Model(models.Model):
            location = OSMField()

        checks = []
        field = Model._meta.get_field("location")
        expected = [
            Error(
                "The OSMField 'location' references the non-existent latitude "
                "field 'location_lat'.",
                hint=None,
                obj=field,
                id="osm_field.E001",
            ),
            Error(
                "The OSMField 'location' references the non-existent longitude "
                "field 'location_lon'.",
                hint=None,
                obj=field,
                id="osm_field.E002",
            ),
        ]
        checks.extend(field.check())
        self.assertEqual(checks, expected) 
Example #3
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.
    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ngettext(singular, plural, n or 0) 
Example #4
Source File: models.py    From bioforum with MIT License 6 votes vote down vote up
def references_model(self, name, app_label=None):
        name_lower = name.lower()
        if name_lower == self.name_lower:
            return True

        # Check we didn't inherit from the model
        models_to_check = [
            base for base in self.bases
            if base is not models.Model and isinstance(base, (models.base.ModelBase, str))
        ]
        # Check we have no FKs/M2Ms with it
        for fname, field in self.fields:
            if field.remote_field:
                models_to_check.append(field.remote_field.model)
        # Now go over all the models and check against them
        for model in models_to_check:
            model_app_label, model_name = self.model_to_key(model)
            if model_name.lower() == name_lower:
                if app_label is None or not model_app_label or model_app_label == app_label:
                    return True
        return False 
Example #5
Source File: test_process_with_django.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def define_projection_record_class(self):
        class ProjectionRecord(models.Model):
            uid = models.BigAutoField(primary_key=True)

            # Sequence ID (e.g. an entity or aggregate ID).
            projection_id = models.UUIDField()

            # State of the item (serialized dict, possibly encrypted).
            state = models.TextField()

            class Meta:
                db_table = "projections"
                app_label = "projections"
                managed = False

        self.projection_record_class = ProjectionRecord 
Example #6
Source File: util.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example #7
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': opts.verbose_name,
        'verbose_name_plural': opts.verbose_name_plural,
    } 
Example #8
Source File: state.py    From bioforum with MIT License 6 votes vote down vote up
def render(self, apps):
        """Create a Model object from our current state into the given apps."""
        # First, make a Meta object
        meta_contents = {'app_label': self.app_label, "apps": apps}
        meta_contents.update(self.options)
        meta = type("Meta", (), meta_contents)
        # Then, work out our bases
        try:
            bases = tuple(
                (apps.get_model(base) if isinstance(base, str) else base)
                for base in self.bases
            )
        except LookupError:
            raise InvalidBasesError("Cannot resolve one or more bases from %r" % (self.bases,))
        # Turn fields into a dict for the body, add other bits
        body = {name: field.clone() for name, field in self.fields}
        body['Meta'] = meta
        body['__module__'] = "__fake__"

        # Restore managers
        body.update(self.construct_managers())
        # Then, make a Model object (apps.register_model is called in __new__)
        return type(self.name, bases, body) 
Example #9
Source File: related_lookups.py    From bioforum with MIT License 6 votes vote down vote up
def get_normalized_value(value, lhs):
    from django.db.models import Model
    if isinstance(value, Model):
        value_list = []
        sources = lhs.output_field.get_path_info()[-1].target_fields
        for source in sources:
            while not isinstance(value, source.model) and source.remote_field:
                source = source.remote_field.model._meta.get_field(source.remote_field.field_name)
            try:
                value_list.append(getattr(value, source.attname))
            except AttributeError:
                # A case like Restaurant.objects.filter(place=restaurant_instance),
                # where place is a OneToOneField and the primary key of Restaurant.
                return (value.pk,)
        return tuple(value_list)
    if not isinstance(value, tuple):
        return (value,)
    return value 
Example #10
Source File: related.py    From bioforum with MIT License 6 votes vote down vote up
def resolve_relation(scope_model, relation):
    """
    Transform relation into a model or fully-qualified model string of the form
    "app_label.ModelName", relative to scope_model.

    The relation argument can be:
      * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
        the model argument will be returned.
      * A bare model name without an app_label, in which case scope_model's
        app_label will be prepended.
      * An "app_label.ModelName" string.
      * A model class, which will be returned unchanged.
    """
    # Check for recursive relations
    if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
        relation = scope_model

    # Look for an "app.Model" relation
    if isinstance(relation, str):
        if "." not in relation:
            relation = "%s.%s" % (scope_model._meta.app_label, relation)

    return relation 
Example #11
Source File: state.py    From bioforum with MIT License 6 votes vote down vote up
def _get_related_models(m):
    """Return all models that have a direct relationship to the given model."""
    related_models = [
        subclass for subclass in m.__subclasses__()
        if issubclass(subclass, models.Model)
    ]
    related_fields_models = set()
    for f in m._meta.get_fields(include_parents=True, include_hidden=True):
        if f.is_relation and f.related_model is not None and not isinstance(f.related_model, str):
            related_fields_models.add(f.model)
            related_models.append(f.related_model)
    # Reverse accessors of foreign keys to proxy models are attached to their
    # concrete proxied model.
    opts = m._meta
    if opts.proxy and m in related_fields_models:
        related_models.append(opts.concrete_model)
    return related_models 
Example #12
Source File: models.py    From django-angularjs-blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def serializer(self, time_format='timestamp', deep=False):
        # print self._meta.fields
        attr_list = [f.name for f in self._meta.fields]
        dic_list = {}
        if time_format == 'timestamp':
            date_func = datetime_to_timestamp
        elif time_format == 'utc':
            date_func = datetime_to_utc_string
        else:
            date_func = datetime_to_string
        # print attr_list
        for itm in attr_list:
            if isinstance(getattr(self, itm), models.Model):
                if deep:
                    dic_list[itm] = getattr(self, itm).serializer(time_format, deep)
            elif isinstance(getattr(self, itm), datetime.datetime):
                dic_list[itm] = date_func(getattr(self, itm))
            else:
                dic_list[itm] = getattr(self, itm)
        return dic_list 
Example #13
Source File: test_apps.py    From django-admin-view-permission with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        class Meta:
            permissions = (
                ("copy_apptestmodel3", "Can copy apptestmodel3"),
            )

        attrs_1 = {
            '__module__': 'tests.test_app.models',
        }
        attrs_2 = {
            '__module__': 'tests.test_app.models',
            'Meta': Meta,
        }

        self.appconfig = apps.get_app_config('test_app')
        self.model1 = type(str('AppTestModel1'), (models.Model, ),
                           attrs_1.copy())
        self.model2 = type(str('AppTestModel2'), (models.Model, ),
                           attrs_1.copy())
        self.model3 = type(str('AppTestModel3'), (models.Model, ),
                           attrs_2.copy()) 
Example #14
Source File: test_fields.py    From django-osm-field with MIT License 6 votes vote down vote up
def test_missing_fields_exclicitly_given(self):
        class Model(models.Model):
            location = OSMField(lat_field="lat", lon_field="lon")

        checks = []
        field = Model._meta.get_field("location")
        expected = [
            Error(
                "The OSMField 'location' references the non-existent latitude "
                "field 'lat'.",
                hint=None,
                obj=field,
                id="osm_field.E001",
            ),
            Error(
                "The OSMField 'location' references the non-existent longitude "
                "field 'lon'.",
                hint=None,
                obj=field,
                id="osm_field.E002",
            ),
        ]
        checks.extend(field.check())
        self.assertEqual(checks, expected) 
Example #15
Source File: registry.py    From django-actions-logger with MIT License 6 votes vote down vote up
def register(self, model, include_fields=[], exclude_fields=[]):
        """
        Register a model with actionslog. Actionslog will then track mutations on this model's instances.

        :param model: The model to register.
        :type model: Model
        :param include_fields: The fields to include. Implicitly excludes all other fields.
        :type include_fields: list
        :param exclude_fields: The fields to exclude. Overrides the fields to include.
        :type exclude_fields: list
        """
        if issubclass(model, Model):
            self._registry[model] = {
                'include_fields': include_fields,
                'exclude_fields': exclude_fields,
            }
            self._connect_signals(model)
        else:
            raise TypeError("Supplied model is not a valid model.") 
Example #16
Source File: validation.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def validate_inlines(self, cls, model):
        " Validate inline model admin classes. "
        from django.contrib.admin.options import BaseModelAdmin
        if hasattr(cls, 'inlines'):
            check_isseq(cls, 'inlines', cls.inlines)
            for idx, inline in enumerate(cls.inlines):
                if not issubclass(inline, BaseModelAdmin):
                    raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
                            "from BaseModelAdmin." % (cls.__name__, idx))
                if not inline.model:
                    raise ImproperlyConfigured("'model' is a required attribute "
                            "of '%s.inlines[%d]'." % (cls.__name__, idx))
                if not issubclass(inline.model, models.Model):
                    raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
                            "inherit from models.Model." % (cls.__name__, idx))
                inline.validate(inline.model)
                self.check_inline(inline, model) 
Example #17
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example #18
Source File: models.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example #19
Source File: models.py    From django-angularjs-blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def serializer(self, time_format='timestamp', deep=False):
        # print self._meta.fields
        attr_list = [f.name for f in self._meta.fields]
        dic_list = {}
        if time_format == 'timestamp':
            date_func = datetime_to_timestamp
        elif time_format == 'utc':
            date_func = datetime_to_utc_string
        else:
            date_func = datetime_to_string
        # print attr_list
        for itm in attr_list:
            if isinstance(getattr(self, itm), models.Model):
                if deep:
                    dic_list[itm] = getattr(self, itm).serializer(time_format, deep)
            elif isinstance(getattr(self, itm), datetime.datetime):
                dic_list[itm] = date_func(getattr(self, itm))
            else:
                dic_list[itm] = getattr(self, itm)
        return dic_list 
Example #20
Source File: models.py    From django-angularjs-blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def serializer(self, time_format='timestamp', deep=False):
        # print self._meta.fields
        attr_list = [f.name for f in self._meta.fields]
        dic_list = {}
        if time_format == 'timestamp':
            date_func = datetime_to_timestamp
        elif time_format == 'utc':
            date_func = datetime_to_utc_string
        else:
            date_func = datetime_to_string
        # print attr_list
        for itm in attr_list:
            if isinstance(getattr(self, itm), models.Model):
                if deep:
                    dic_list[itm] = getattr(self, itm).serializer(time_format, deep)
            elif isinstance(getattr(self, itm), datetime.datetime):
                dic_list[itm] = date_func(getattr(self, itm))
            else:
                dic_list[itm] = getattr(self, itm)
        return dic_list 
Example #21
Source File: models.py    From bioforum with MIT License 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__qualname__,
            [],
            kwargs
        ) 
Example #22
Source File: backend.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def check_object_support(obj):
    """
    Returns the permission check method for supported methods and classes
    """
    if isinstance(obj, models.Model) and hasattr(obj, 'has_perm'):
        return obj.has_perm
    if inspect.isclass(obj) and issubclass(obj, models.Model) and hasattr(obj, 'has_model_perm'):
        return obj.has_model_perm
    return False 
Example #23
Source File: checks.py    From bioforum with MIT License 5 votes vote down vote up
def _check_inlines_item(self, obj, model, inline, label):
        """ Check one inline model admin. """
        inline_label = inline.__module__ + '.' + inline.__name__

        from django.contrib.admin.options import InlineModelAdmin

        if not issubclass(inline, InlineModelAdmin):
            return [
                checks.Error(
                    "'%s' must inherit from 'InlineModelAdmin'." % inline_label,
                    obj=obj.__class__,
                    id='admin.E104',
                )
            ]
        elif not inline.model:
            return [
                checks.Error(
                    "'%s' must have a 'model' attribute." % inline_label,
                    obj=obj.__class__,
                    id='admin.E105',
                )
            ]
        elif not issubclass(inline.model, models.Model):
            return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106')
        else:
            return inline(model, obj.admin_site).check() 
Example #24
Source File: models.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def get_singular(model):
    if issubclass(model, models.base.Model):
        model = model.__name__
    return model.lower() 
Example #25
Source File: models.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def get_plural(model):
    if issubclass(model, models.base.Model):
        model = model.__name__
    return model.lower() + 's' 
Example #26
Source File: links.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def parser_for_model(self, model):
        if isinstance(model, models.Model):
            model = model._meta.label
        return self.model_links.get(model, None) 
Example #27
Source File: registry.py    From django-actions-logger with MIT License 5 votes vote down vote up
def contains(self, model):
        """
        Check if a model is registered with actionslog.

        :param model: The model to check.
        :type model: Model
        :return: Whether the model has been registered.
        :rtype: bool
        """
        return model in self._registry 
Example #28
Source File: models.py    From django-actions-logger with MIT License 5 votes vote down vote up
def get_for_model(self, model):
        """
        Get log entries for all objects of a specified type.
        :param model: The model to get log entries for.
        :type model: class
        :return: QuerySet of log entries for the given model.
        :rtype: QuerySet
        """
        # Return empty queryset if the given object is not valid.
        if not issubclass(model, models.Model):
            return self.none()

        ct = ContentType.objects.get_for_model(model)

        return self.filter(content_type=ct) 
Example #29
Source File: models.py    From django-actions-logger with MIT License 5 votes vote down vote up
def _get_pk_value(self, instance):
        """
        Get the primary key field value for a model instance.
        :param instance: The model instance to get the primary key for.
        :type instance: Model
        :return: The primary key value of the given model instance.
        """
        pk_field = instance._meta.pk.name
        pk = getattr(instance, pk_field, None)

        # Check to make sure that we got an pk not a model object.
        if isinstance(pk, models.Model):
            pk = self._get_pk_value(pk)
        return pk 
Example #30
Source File: links.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def register_reverse_link(self, parser_regex, url_name, model=None, reverse=None):
        """
        Registers a new parser for links using Django urlconf
        :param parser_regex: string or regex object
        :param url_name: urlconf name
        :param model: model label (app_label.model_name) or model class (used by fir_relations)
        :param reverse: string template to render object id to text (used by fir_relations)
        """
        if not isinstance(parser_regex, re._pattern_type):
            parser_regex = re.compile(parser_regex)
        self.reverse_links.append((parser_regex, url_name))
        if model is not None:
            if not isinstance(model, six.string_types) and issubclass(models.Model, model):
                model = model._meta.label
            self.model_links[model] = (parser_regex, url_name, reverse)