当前位置: 首页>>代码示例>>Python>>正文


Python models.ManyToManyField方法代码示例

本文整理汇总了Python中django.db.models.ManyToManyField方法的典型用法代码示例。如果您正苦于以下问题:Python models.ManyToManyField方法的具体用法?Python models.ManyToManyField怎么用?Python models.ManyToManyField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models的用法示例。


在下文中一共展示了models.ManyToManyField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _dict

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def _dict(self):
        exclude = ['operator_id', 'creator_id', 'created', 'modified']
        opts = self._meta
        data = {}
        keys = [f.attname for f in opts.fields]
        for f in chain(opts.many_to_many):
            #if isinstance(f, models.ManyToManyField):
            if self.pk is None:
                data[f.name] = []
            else:
                data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
        original = { k:self.__dict__.get(k) for k in keys if k not in exclude }
        data.update(**original)
        for key, value in data.items():
            if isinstance(value, timezone.datetime):
                value = formats.localize(timezone.template_localtime(value))
            data.update(**{key: value})
        return data 
开发者ID:Wenvki,项目名称:django-idcops,代码行数:20,代码来源:models.py

示例2: __set__

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def __set__(self, instance, value):
        if not self.related.field.rel.through._meta.auto_created:
            opts = self.related.field.rel.through._meta
            raise AttributeError(
                "Cannot set values on a ManyToManyField which specifies an "
                "intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
            )

        # Force evaluation of `value` in case it's a queryset whose
        # value could be affected by `manager.clear()`. Refs #19816.
        value = tuple(value)

        manager = self.__get__(instance)
        db = router.db_for_write(manager.through, instance=manager.instance)
        with transaction.atomic(using=db, savepoint=False):
            manager.clear()
            manager.add(*value) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:related.py

示例3: _check_ignored_options

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def _check_ignored_options(self, **kwargs):
        warnings = []

        if self.null:
            warnings.append(
                checks.Warning(
                    'null has no effect on ManyToManyField.',
                    hint=None,
                    obj=self,
                    id='fields.W340',
                )
            )

        if len(self._validators) > 0:
            warnings.append(
                checks.Warning(
                    'ManyToManyField does not support validators.',
                    hint=None,
                    obj=self,
                    id='fields.W341',
                )
            )

        return warnings 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:26,代码来源:related.py

示例4: validate_list_display

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def validate_list_display(self, cls, model):
        " Validate that list_display only contains fields or usable attributes. "
        if hasattr(cls, 'list_display'):
            check_isseq(cls, 'list_display', cls.list_display)
            for idx, field in enumerate(cls.list_display):
                if not callable(field):
                    if not hasattr(cls, field):
                        if not hasattr(model, field):
                            try:
                                model._meta.get_field(field)
                            except FieldDoesNotExist:
                                raise ImproperlyConfigured(
                                    "%s.list_display[%d], %r is not a callable or "
                                    "an attribute of %r or found in the model %r."
                                    % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)
                                )
                        else:
                            # getattr(model, field) could be an X_RelatedObjectsDescriptor
                            f = fetch_attr(cls, model, "list_display[%d]" % idx, field)
                            if isinstance(f, models.ManyToManyField):
                                raise ImproperlyConfigured(
                                    "'%s.list_display[%d]', '%s' is a ManyToManyField "
                                    "which is not supported."
                                    % (cls.__name__, idx, field)
                                ) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:27,代码来源:validation.py

示例5: has_perm

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def has_perm(self, user, permission):
    if user.is_superuser:
        return True
    if isinstance(permission, six.string_types):
        permission = [permission, ]
    if user.has_perms(permission):
        return True
    if self._authorization_meta.owner_field and self._authorization_meta.owner_permission and \
       self._authorization_meta.owner_permission in permission and \
       user.pk == getattr(self, self._authorization_meta.owner_field).pk:
        return True
    paths = self._authorization_meta.model.get_authorization_paths(user, permission)
    if not paths.count():
        return False
    for field in self._authorization_meta.fields:
        f = self._meta.get_field(field)
        relation = getattr(self, field)
        if isinstance(f, models.ManyToManyField):
            qs_filter = reduce(lambda x, y: x | y, [Q(path__startswith=path) for path in paths])
            if relation.filter(qs_filter).distinct().exists():
                return True
        elif isinstance(f, models.ForeignKey):
            if relation is not None and any(relation.path.startswith(p) for p in paths):
                return True
    return False 
开发者ID:certsocietegenerale,项目名称:FIR,代码行数:27,代码来源:decorator.py

示例6: _check_prepopulated_fields_key

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def _check_prepopulated_fields_key(self, obj, model, field_name, label):
        """ Check a key of `prepopulated_fields` dictionary, i.e. check that it
        is a name of existing field and the field is one of the allowed types.
        """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E027')
        else:
            if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which must not be a DateTimeField, "
                        "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name),
                        obj=obj.__class__,
                        id='admin.E028',
                    )
                ]
            else:
                return [] 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:24,代码来源:checks.py

示例7: formfield_for_dbfield

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.rel.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
开发者ID:stormsha,项目名称:StormOnline,代码行数:10,代码来源:edit.py

示例8: get_field_style

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
开发者ID:stormsha,项目名称:StormOnline,代码行数:16,代码来源:edit.py

示例9: get_form_datas

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
开发者ID:stormsha,项目名称:StormOnline,代码行数:17,代码来源:edit.py

示例10: get_field_style

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
开发者ID:stormsha,项目名称:StormOnline,代码行数:8,代码来源:multiselect.py

示例11: formfield_for_dbfield

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
开发者ID:stormsha,项目名称:StormOnline,代码行数:10,代码来源:quickform.py

示例12: _connect_signal

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def _connect_signal(self, index):
        """Create signals for building indexes."""
        post_save_signal = ElasticSignal(index, "build")
        post_save_signal.connect(post_save, sender=index.object_type)
        self.signals.append(post_save_signal)

        post_delete_signal = ElasticSignal(index, "remove_object")
        post_delete_signal.connect(post_delete, sender=index.object_type)
        self.signals.append(post_delete_signal)

        # Connect signals for all dependencies.
        for dependency in index.get_dependencies():
            # Automatically convert m2m fields to dependencies.
            if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)):
                dependency = ManyToManyDependency(dependency)
            elif isinstance(dependency, ReverseManyToOneDescriptor):
                dependency = ReverseManyToOneDependency(dependency)
            elif isinstance(dependency, ForwardManyToOneDescriptor):
                dependency = ForwardManyToOneDependency(dependency)
            elif not isinstance(dependency, Dependency):
                raise TypeError(
                    "Unsupported dependency type: {}".format(repr(dependency))
                )

            signal = dependency.connect(index)
            self.signals.extend(signal) 
开发者ID:genialis,项目名称:resolwe,代码行数:28,代码来源:builder.py

示例13: get_form_kwargs

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def get_form_kwargs(self):
        kwargs = super(NewModelView, self).get_form_kwargs()
        params = self.request.GET.dict()
        mfields = [f.attname for f in self.opts.fields]
        for k in params.keys():
            if k in mfields:
                kwargs.update({k: params[k]})
        related_models = []
        for f in self.opts.get_fields():
            if isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                if f.related_model:
                    related_models.append(f.related_model)
        if User in related_models:
            kwargs.update({'user': self.request.user})
        return kwargs 
开发者ID:Wenvki,项目名称:django-idcops,代码行数:17,代码来源:edit.py

示例14: setUp

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def setUp(self):
        self.time_func = TimeFormatFactory.get_time_func('string')
        # DATABASES = {
        #     'default': {
        #     'ENGINE': 'django.db.backends.sqlite3',
        #     'NAME': ':memory:',
        #     'USER': '',                      # Not used with sqlite3.
        #     'PASSWORD': '',                  # Not used with sqlite3.
        #     'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        #     'PORT': '',
        #     }
        # }
        # settings.configure(DATABASES=DATABASES, DEBUG=True)
        # class TestAuthor(models.Model):
        #     name = models.CharField(default='test_author')
        #
        #     def __unicode__(self):
        #         return self.name
        #
        # class TestTags(models.Model):
        #     tag = models.CharField(default='test_tag')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        # class TestArticle(models.Model):
        #     title = models.CharField(default='test')
        #     content = models.CharField(default='test')
        #     author = models.ForeignKey(TestAuthor, related_name='author_art')
        #     tags = models.ManyToManyField(TestTags, related_name='tag_art')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        #
        # self.author = TestAuthor()
        # self.author.save()
        # tags = TestTags(tag='tag1')
        # tags.save()
        # self.article = TestArticle(author=self.author)
        # self.article.tags.add(tags)
        # self.article.save() 
开发者ID:bluedazzle,项目名称:django-angularjs-blog,代码行数:40,代码来源:test_Serializer.py

示例15: _generate_added_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ManyToManyField [as 别名]
def _generate_added_field(self, app_label, model_name, field_name):
        field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
        # Fields that are foreignkeys/m2ms depend on stuff
        dependencies = []
        if field.rel and field.rel.to:
            # Account for FKs to swappable models
            swappable_setting = getattr(field, 'swappable_setting', None)
            if swappable_setting is not None:
                dep_app_label = "__setting__"
                dep_object_name = swappable_setting
            else:
                dep_app_label = field.rel.to._meta.app_label
                dep_object_name = field.rel.to._meta.object_name
            dependencies = [(dep_app_label, dep_object_name, None, True)]
            if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                dependencies.append((
                    field.rel.through._meta.app_label,
                    field.rel.through._meta.object_name,
                    None,
                    True,
                ))
        # You can't just add NOT NULL fields with no default or fields
        # which don't allow empty strings as default.
        preserve_default = True
        if (not field.null and not field.has_default() and
                not isinstance(field, models.ManyToManyField) and
                not (field.blank and field.empty_strings_allowed)):
            field = field.clone()
            field.default = self.questioner.ask_not_null_addition(field_name, model_name)
            preserve_default = False
        self.add_operation(
            app_label,
            operations.AddField(
                model_name=model_name,
                name=field_name,
                field=field,
                preserve_default=preserve_default,
            ),
            dependencies=dependencies,
        ) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:42,代码来源:autodetector.py


注:本文中的django.db.models.ManyToManyField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。