Python django.db.models.Model() Examples

The following are 30 code examples for showing how to use django.db.models.Model(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: StormOnline   Author: stormsha   File: util.py    License: Apache License 2.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 2
Project: StormOnline   Author: stormsha   File: util.py    License: 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 3
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 4
Project: django-angularjs-blog   Author: bluedazzle   File: models.py    License: 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 5
Project: django-angularjs-blog   Author: bluedazzle   File: models.py    License: 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 6
Project: django-angularjs-blog   Author: bluedazzle   File: models.py    License: 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 7
Project: GTDWeb   Author: lanbing510   File: models.py    License: 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 8
Project: GTDWeb   Author: lanbing510   File: utils.py    License: 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 9
Project: GTDWeb   Author: lanbing510   File: validation.py    License: 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 10
Project: django-osm-field   Author: MarkusH   File: test_fields.py    License: 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 11
Project: django-osm-field   Author: MarkusH   File: test_fields.py    License: 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 12
Project: django-actions-logger   Author: shtalinberg   File: registry.py    License: 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 13
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
Project: bioforum   Author: reBiocoder   File: models.py    License: 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 15
Project: bioforum   Author: reBiocoder   File: models.py    License: 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 16
Project: bioforum   Author: reBiocoder   File: state.py    License: 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 17
Project: bioforum   Author: reBiocoder   File: state.py    License: 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 18
Project: bioforum   Author: reBiocoder   File: related_lookups.py    License: 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 19
Project: bioforum   Author: reBiocoder   File: related.py    License: 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 20
Project: bioforum   Author: reBiocoder   File: utils.py    License: 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 21
Project: bioforum   Author: reBiocoder   File: utils.py    License: 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 22
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    License: MIT License 5 votes vote down vote up
def _to_model(self, model_or_instance):
        return (model_or_instance.__class__
                if isinstance(model_or_instance, models.Model)
                else model_or_instance) 
Example 23
Project: django-click   Author: GaretJax   File: params.py    License: MIT License 5 votes vote down vote up
def __init__(self, qs, lookup="pk"):
        from django.db import models

        if isinstance(qs, type) and issubclass(qs, models.Model):
            qs = qs.objects.all()
        self.qs = qs
        self.name = "{}.{}".format(qs.model._meta.app_label, qs.model.__name__,)
        self.lookup = lookup 
Example 24
Project: Servo   Author: fpsw   File: forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def serialize(self):
        import datetime
        from django.db.models import Model
        cd = self.cleaned_data

        for k, v in cd.iteritems():
            if isinstance(v, datetime.datetime):
                cd[k] = str(v)
            if isinstance(v, Model):
                cd[k] = v.pk

        return cd 
Example 25
Project: django-accounting   Author: dulacp   File: introspection_filters.py    License: MIT License 5 votes vote down vote up
def get_model_verbose_name(instance):
    if isinstance(instance, Model):
        return instance._meta.verbose_name.title()
    return '<unknown>' 
Example 26
Project: django-rest-registration   Author: apragacz   File: checks.py    License: MIT License 5 votes vote down vote up
def _are_login_fields_unique() -> bool:
    user_cls = get_user_model()  # type: Type[Model]
    user_meta = user_cls._meta  # pylint: disable=protected-access
    return all(
        is_model_field_unique(user_meta.get_field(field_name))
        for field_name in get_user_login_field_names()) 
Example 27
Project: coursys   Author: sfu-fas   File: handlers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_config(self, name, value):
        field = self.CONFIG_FIELDS[name]
        if value is None:
            raw_value = None
        elif isinstance(value, models.Model):
            raw_value = str(value.pk)
        else:
            raw_value = str(field.prepare_value(value))

        self.event.config[name] = raw_value 
Example 28
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_config(self, name, value):
        field = self.CONFIG_FIELDS[name]
        if value is None:
            raw_value = None
        elif isinstance(value, models.Model):
            raw_value = str(value.pk)
        else:
            raw_value = str(field.prepare_value(value))

        self.event.config[name] = raw_value

    # Other ways to create a new handler instance 
Example 29
Project: drf-flex-fields   Author: rsinger86   File: filter_backends.py    License: MIT License 5 votes vote down vote up
def _get_field(field_name: str, model: models.Model) -> Optional[models.Field]:
        try:
            # noinspection PyProtectedMember
            return model._meta.get_field(field_name)
        except models.FieldDoesNotExist:
            return None 
Example 30
Project: wagtailinvoices   Author: SableWalnut   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_invoice_model(cls):
        if isinstance(cls.invoice_model, models.Model):
            return cls.invoice_model
        elif isinstance(cls.invoice_model, string_types):
            return resolve_model_string(cls.invoice_model, cls._meta.app_label)
        else:
            raise ValueError('Can not resolve {0}.invoice_model in to a model: {1!r}'.format(
                cls.__name__, cls.invoice_model))