Python django.db.models.fields.related.ManyToManyField() Examples

The following are 21 code examples of django.db.models.fields.related.ManyToManyField(). 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.fields.related , or try the search function .
Example #1
Source File: options.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_all_related_objects(self, local_only=False, include_hidden=False,
                                include_proxy_eq=False):

        include_parents = True if local_only is False else PROXY_PARENTS
        fields = self._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents,
            include_hidden=include_hidden,
        )
        fields = (obj for obj in fields if not isinstance(obj.field, ManyToManyField))
        if include_proxy_eq:
            children = chain.from_iterable(c._relation_tree
                                           for c in self.concrete_model._meta.proxied_children
                                           if c is not self)
            relations = (f.rel for f in children
                         if include_hidden or not f.rel.field.rel.is_hidden())
            fields = chain(fields, relations)
        return list(fields) 
Example #2
Source File: options.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def get_all_related_objects(self, local_only=False, include_hidden=False,
                                include_proxy_eq=False):

        include_parents = True if local_only is False else PROXY_PARENTS
        fields = self._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents,
            include_hidden=include_hidden,
        )
        fields = (obj for obj in fields if not isinstance(obj.field, ManyToManyField))
        if include_proxy_eq:
            children = chain.from_iterable(c._relation_tree
                                           for c in self.concrete_model._meta.proxied_children
                                           if c is not self)
            relations = (f.remote_field for f in children
                         if include_hidden or not f.remote_field.field.remote_field.is_hidden())
            fields = chain(fields, relations)
        return list(fields) 
Example #3
Source File: utils.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def reviewable_data_has_changed(obj, new_key_vals, exempt_fields=None):
    """
    Check whether serialized data for the object has changed.

    Args:
        obj (Object): Object representing the persisted state
        new_key_vals (dict_items): List of (key,value) tuples representing the new state
        exempt_fields (list): List of field names where a change does not affect review status

    Returns:
        bool for whether data for any reviewable fields has changed
    """
    changed = False
    exempt_fields = exempt_fields or []
    for key, new_value in [x for x in new_key_vals if x[0] not in exempt_fields]:
        original_value = getattr(obj, key, None)
        if isinstance(new_value, list):
            field_class = obj.__class__._meta.get_field(key).__class__
            original_value_elements = original_value.all()
            if len(new_value) != original_value_elements.count():
                changed = True
            # Just use set compare since none of our fields require duplicates
            elif field_class == ManyToManyField and set(new_value) != set(original_value_elements):
                changed = True
            elif field_class == SortedManyToManyField:
                for new_value_element, original_value_element in zip(new_value, original_value_elements):
                    if new_value_element != original_value_element:
                        changed = True
        elif new_value != original_value:
            changed = True
    return changed 
Example #4
Source File: serializers.py    From django-elasticsearch with MIT License 5 votes vote down vote up
def serialize_field(self, instance, field_name):
        method_name = 'serialize_{0}'.format(field_name)
        if hasattr(self, method_name):
            return getattr(self, method_name)(instance, field_name)

        try:
            field = self.model._meta.get_field(field_name)
        except FieldDoesNotExist:
            # Abstract field
            pass
        else:
            field_type_method_name = 'serialize_type_{0}'.format(
                field.__class__.__name__.lower())
            if hasattr(self, field_type_method_name):
                return getattr(self, field_type_method_name)(instance, field_name)

            if field.rel:
                # M2M
                if isinstance(field, ManyToManyField):
                    return [self.nested_serialize(r)
                            for r in getattr(instance, field.name).all()]

                rel = getattr(instance, field.name)
                # FK, OtO
                if rel:  # should be a model instance
                    if self.cur_depth >= self.max_depth:
                        return

                    return self.nested_serialize(rel)

        try:
            return getattr(instance, field_name)
        except AttributeError:
            raise AttributeError("The serializer doesn't know how to serialize {0}, "
                                 "please provide it a {1} method."
                                 "".format(field_name, method_name)) 
Example #5
Source File: serializers.py    From django-elasticsearch with MIT License 5 votes vote down vote up
def deserialize_field(self, source, field_name):
        method_name = 'deserialize_{0}'.format(field_name)
        if hasattr(self, method_name):
            return getattr(self, method_name)(source, field_name)

        field = self.model._meta.get_field(field_name)
        field_type_method_name = 'deserialize_type_{0}'.format(
            field.__class__.__name__.lower())
        if hasattr(self, field_type_method_name):
            return getattr(self, field_type_method_name)(source, field_name)

        val = source.get(field_name)

        # datetime
        typ = field.get_internal_type()
        if val and typ in ('DateField', 'DateTimeField'):
            return datetime.datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f')

        if field.rel:
            # M2M
            if isinstance(field, ManyToManyField):
                raise AttributeError

            # FK, OtO
            return self.nested_deserialize(field, source.get(field_name))

        return source.get(field_name) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_m2m_field(self):
        field_info = self._details(Person, Person._meta.get_field('m2m_base'))
        self.assertEqual(field_info[1:], (BasePerson, True, True))
        self.assertIsInstance(field_info[0], related.ManyToManyField) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_m2m_field(self):
        field_info = self._details(Person, Person._meta.get_field('m2m_base'))
        self.assertEqual(field_info[1:], (BasePerson, True, True))
        self.assertIsInstance(field_info[0], related.ManyToManyField) 
Example #8
Source File: options.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_all_related_m2m_objects_with_model(self):
        fields = self._get_fields(forward=False, reverse=True, include_hidden=True)
        return [self._map_model(obj) for obj in fields if isinstance(obj.field, ManyToManyField)] 
Example #9
Source File: options.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_all_related_many_to_many_objects(self, local_only=False):
        include_parents = True if local_only is not True else PROXY_PARENTS
        fields = self._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents, include_hidden=True
        )
        return [obj for obj in fields if isinstance(obj.field, ManyToManyField)] 
Example #10
Source File: models.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def model_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    """
    # avoid a circular import
    from django.db.models.fields.related import ManyToManyField
    opts = instance._meta
    data = {}
    for f in chain(opts.concrete_fields, opts.virtual_fields, opts.many_to_many):
        if not getattr(f, 'editable', False):
            continue
        if fields and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if isinstance(f, ManyToManyField):
            # If the object doesn't have a primary key yet, just use an empty
            # list for its m2m fields. Calling f.value_from_object will raise
            # an exception.
            if instance.pk is None:
                data[f.name] = []
            else:
                # MultipleChoiceWidget needs a list of pks, not object instances.
                qs = f.value_from_object(instance)
                if qs._result_cache is not None:
                    data[f.name] = [item.pk for item in qs]
                else:
                    data[f.name] = list(qs.values_list('pk', flat=True))
        else:
            data[f.name] = f.value_from_object(instance)
    return data 
Example #11
Source File: models.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def model_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    """
    # avoid a circular import
    from django.db.models.fields.related import ManyToManyField
    opts = instance._meta
    data = {}
    for f in opts.fields + opts.many_to_many:
        if not f.editable:
            continue
        if fields and not f.name in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if isinstance(f, ManyToManyField):
            # If the object doesn't have a primary key yet, just use an empty
            # list for its m2m fields. Calling f.value_from_object will raise
            # an exception.
            if instance.pk is None:
                data[f.name] = []
            else:
                # MultipleChoiceWidget needs a list of pks, not object instances.
                data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
        else:
            data[f.name] = f.value_from_object(instance)
    return data 
Example #12
Source File: views.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        try:
            msg = _("%(model_name)s '%(instance)s' deleted.") % {
                'model_name': self.verbose_name, 'instance': self.instance
            }
            self.delete_instance()
            messages.success(request, msg)
            return redirect(self.index_url)
        except models.ProtectedError:
            linked_objects = []
            fields = self.model._meta.fields_map.values()
            fields = (obj for obj in fields if not isinstance(
                obj.field, ManyToManyField))
            for rel in fields:
                if rel.on_delete == models.PROTECT:
                    if isinstance(rel, OneToOneRel):
                        try:
                            obj = getattr(self.instance, rel.get_accessor_name())
                        except ObjectDoesNotExist:
                            pass
                        else:
                            linked_objects.append(obj)
                    else:
                        qs = getattr(self.instance, rel.get_accessor_name())
                        for obj in qs.all():
                            linked_objects.append(obj)
            context = self.get_context_data(
                protected_error=True,
                linked_objects=linked_objects
            )
            return self.render_to_response(context) 
Example #13
Source File: mail.py    From django-db-mailer with GNU General Public License v2.0 5 votes vote down vote up
def _model_to_dict(instance):
        opts, data = getattr(instance, '_meta'), dict()
        for f in opts.fields + opts.many_to_many:
            if isinstance(f, ManyToManyField):
                if instance.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = [
                        item.pk for item in f.value_from_object(instance)]
            elif isinstance(f, ForeignKey):
                if getattr(instance, f.name):
                    data[f.name] = getattr(instance, f.name).__str__()
            else:
                data[f.name] = f.value_from_object(instance)
        return data 
Example #14
Source File: common.py    From Joy_QA_Platform with Apache License 2.0 5 votes vote down vote up
def to_dict(instance):
    opts = instance._meta
    data = {}
    for f in opts.concrete_fields + opts.many_to_many:
        if isinstance(f, ManyToManyField):
            if instance.pk is None:
                data[f.name] = []
            else:
                data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
        else:
            data[f.name] = f.value_from_object(instance)
    return data 
Example #15
Source File: models.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def to_dict(self):
        data = {}

        # Iterate over croncrete and many-to-many fields
        for field in self._meta.concrete_fields + self._meta.many_to_many:
            value = None

            # If the value of the field is another model, fetch an instance of it
            # Exception made of tags for which we just retrieve the list of them for later
            # conversion to simple strings
            if isinstance(field, ForeignKey):
                value = self.__getattribute__(field.name)
            elif isinstance(field, ManyToManyField):
                value = list(self.__getattribute__(field.name).all())
            elif isinstance(field, TaggableManager):
                value = list(self.__getattribute__(field.name).all())
            else:
                value = self.__getattribute__(field.name)

            # If the instance of a model as a to_dict() function, call it
            if isinstance(value, TemplateModel):
                data[field.name] = value.to_dict()
            elif isinstance(value, list):
                data[field.name] = []
                for element in value:
                    if isinstance(element, TemplateModel):
                        data[field.name].append(element.to_dict())
                    else:
                        data[field.name].append(str(element))
            else:
                data[field.name] = value

        return data 
Example #16
Source File: filters.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def choices(self, cl):
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        yield {
            'selected': self.lookup_val is None and not self.lookup_val_isnull,
            'query_string': cl.get_query_string({},
                [self.lookup_kwarg, self.lookup_kwarg_isnull]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_val == smart_text(pk_val),
                'query_string': cl.get_query_string({
                    self.lookup_kwarg: pk_val,
                }, [self.lookup_kwarg_isnull]),
                'display': val,
            }
        if (isinstance(self.field, ForeignObjectRel) and
                (self.field.field.null or isinstance(self.field.field, ManyToManyField)) or
                hasattr(self.field, 'rel') and (self.field.null or isinstance(self.field, ManyToManyField))):
            yield {
                'selected': bool(self.lookup_val_isnull),
                'query_string': cl.get_query_string({
                    self.lookup_kwarg_isnull: 'True',
                }, [self.lookup_kwarg]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #17
Source File: options.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_all_related_m2m_objects_with_model(self):
        fields = self._get_fields(forward=False, reverse=True, include_hidden=True)
        return [self._map_model(obj) for obj in fields if isinstance(obj.field, ManyToManyField)] 
Example #18
Source File: options.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_all_related_many_to_many_objects(self, local_only=False):
        include_parents = True if local_only is not True else PROXY_PARENTS
        fields = self._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents, include_hidden=True
        )
        return [obj for obj in fields if isinstance(obj.field, ManyToManyField)] 
Example #19
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def model_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    """
    # avoid a circular import
    from django.db.models.fields.related import ManyToManyField
    opts = instance._meta
    data = {}
    for f in chain(opts.concrete_fields, opts.virtual_fields, opts.many_to_many):
        if not getattr(f, 'editable', False):
            continue
        if fields and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if isinstance(f, ManyToManyField):
            # If the object doesn't have a primary key yet, just use an empty
            # list for its m2m fields. Calling f.value_from_object will raise
            # an exception.
            if instance.pk is None:
                data[f.name] = []
            else:
                # MultipleChoiceWidget needs a list of pks, not object instances.
                qs = f.value_from_object(instance)
                if qs._result_cache is not None:
                    data[f.name] = [item.pk for item in qs]
                else:
                    data[f.name] = list(qs.values_list('pk', flat=True))
        else:
            data[f.name] = f.value_from_object(instance)
    return data 
Example #20
Source File: betterJSONSerializer.py    From arches with GNU Affero General Public License v3.0 4 votes vote down vote up
def handle_model(self, instance, fields=None, exclude=None):
        """
        Returns a dict containing the data in ``instance`` suitable for passing as
        a Form's ``initial`` keyword argument.

        ``fields`` is an optional list of field names. If provided, only the named
        fields will be included in the returned dict.

        ``exclude`` is an optional list of field names. If provided, the named
        fields will be excluded from the returned dict, even if they are listed in
        the ``fields`` argument.
        """
        # avoid a circular import
        from django.db.models.fields.related import ManyToManyField, ForeignKey

        opts = instance._meta
        data = {}
        # print '='*40
        properties = [k for k, v in instance.__class__.__dict__.items() if type(v) is property]
        for property_name in properties:
            if fields and property_name not in fields:
                continue
            if exclude and property_name in exclude:
                continue
            data[property_name] = self.handle_object(getattr(instance, property_name))
        for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
            if not getattr(f, "editable", False):
                continue
            if fields and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            if isinstance(f, ForeignKey):
                # Emulate the naming convention used by django when accessing the
                # related model's id field
                # see https://github.com/django/django/blob/master/django/db/models/fields/__init__.py
                val = getattr(instance, f.attname, None)
                data[f.attname] = val
            elif isinstance(f, ManyToManyField):
                # If the object doesn't have a primary key yet, just use an empty
                # list for its m2m fields. Calling f.value_from_object will raise
                # an exception.
                if instance.pk is None:
                    data[f.name] = []
                else:
                    # MultipleChoiceWidget needs a list of pks, not object instances.
                    qs = f.value_from_object(instance)
                    data[f.name] = [item.pk for item in qs]
            else:
                data[f.name] = self.handle_object(f.value_from_object(instance))
        return data 
Example #21
Source File: generate_template_doc.py    From peering-manager with Apache License 2.0 4 votes vote down vote up
def get_model_variables(model):
    variables = []

    for field in model._meta.concrete_fields + model._meta.many_to_many:
        variable = None

        if isinstance(field, ForeignKey):
            variable = "`{}`: {} object".format(
                field.name, get_model_file_link(field.related_model)
            )
        elif isinstance(field, ManyToManyField):
            variable = "`{}`: list of {} objects".format(
                field.name, get_model_file_link(field.related_model)
            )
        elif isinstance(field, TaggableManager):
            variable = "`{}`: list of tags".format(field.name)
        else:
            field_type = None
            if isinstance(field, BooleanField):
                field_type = "boolean"
            elif isinstance(field, CharField):
                field_type = "string"
            elif isinstance(field, TextField):
                field_type = "text"
            elif isinstance(field, DateTimeField):
                field_type = "date"
            elif isinstance(field, InetAddressField):
                field_type = "IP address"
            elif (
                isinstance(field, AutoField)
                or isinstance(field, BigIntegerField)
                or isinstance(field, PositiveIntegerField)
                or isinstance(field, PositiveSmallIntegerField)
            ):
                field_type = "integer".format(field.name)
            else:
                print(
                    "Unknown type for `{}`: {}".format(
                        field.name, field.get_internal_type()
                    )
                )

            if field_type:
                variable = "`{}`: {} value".format(field.name, field_type)

        if variable:
            variables.append(variable)

    return variables