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


Python related.ForeignKey方法代码示例

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


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

示例1: search_placeholder

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def search_placeholder(context):
    cl = context.get('cl')

    # 取消递归,只获取2级
    fields = get_model_fields(cl.model)

    for f in cl.model._meta.fields:
        if isinstance(f, ForeignKey):
            fields.extend(get_model_fields(f.related_model, f.name))

    verboses = []

    for s in cl.search_fields:
        for f in fields:
            if f[0] == s:
                verboses.append(f[1])
                break

    return ",".join(verboses) 
开发者ID:jeeyshe,项目名称:ishare,代码行数:21,代码来源:simpletags.py

示例2: register

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def register(model, field_name=None, related_name=None, lookup_method_name='get_follows'):
    """
    This registers any model class to be follow-able.

    """
    if model in registry:
        return

    registry.append(model)

    if not field_name:
        field_name = 'target_%s' % model._meta.model_name

    if not related_name:
        related_name = 'follow_%s' % model._meta.model_name

    field = ForeignKey(model, related_name=related_name, null=True,
        blank=True, db_index=True)

    field.contribute_to_class(Follow, field_name)
    setattr(model, lookup_method_name, get_followers_for_object)
    model_map[model] = [related_name, field_name] 
开发者ID:peragro,项目名称:django-project,代码行数:24,代码来源:utils.py

示例3: detach

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def detach(self):
        """
        Detaches the instance from its history.

        Similar to creating a new object with the same field values. The id and
        identity fields are set to a new value. The returned object has not
        been saved, call save() afterwards when you are ready to persist the
        object.

        ManyToMany and reverse ForeignKey relations are lost for the detached
        object.

        :return: Versionable
        """
        self.id = self.identity = self.uuid()
        self.version_start_date = self.version_birth_date = get_utc_now()
        self.version_end_date = None
        return self 
开发者ID:swisscom,项目名称:cleanerversion,代码行数:20,代码来源:models.py

示例4: build_schema_from_model

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def build_schema_from_model(model):
    field_mappings = {
        model_fields.BigIntegerField: "INTEGER",
        model_fields.CharField: "STRING",
        model_fields.DateField: "DATE",
        model_fields.FloatField: "FLOAT",
        model_fields.DecimalField: "NUMERIC",
        model_fields.IntegerField: "INTEGER",
        model_fields.BooleanField: "BOOLEAN",
        model_fields.NullBooleanField: "BOOLEAN",
        model_fields.TextField: "STRING",
        related_fields.ForeignKey: "INTEGER",
        related_fields.OneToOneField: "INTEGER",
    }

    fields = [
        (f.name, field_mappings[type(f)])
        for f in model._meta.fields
        if not f.auto_created
    ]

    return build_schema(*fields) 
开发者ID:ebmdatalab,项目名称:openprescribing,代码行数:24,代码来源:bigquery.py

示例5: get_field_set_type

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def get_field_set_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType:
        """ Get a type of __set__ for this specific Django field. """
        target_field = field
        if isinstance(field, ForeignKey):
            target_field = field.target_field

        field_info = helpers.lookup_class_typeinfo(api, target_field.__class__)
        if field_info is None:
            return AnyType(TypeOfAny.from_error)

        field_set_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_set_type',
                                                             is_nullable=self.get_field_nullability(field, method))
        if isinstance(target_field, ArrayField):
            argument_field_type = self.get_field_set_type(api, target_field.base_field, method=method)
            field_set_type = helpers.convert_any_to_type(field_set_type, argument_field_type)
        return field_set_type 
开发者ID:typeddjango,项目名称:django-stubs,代码行数:18,代码来源:context.py

示例6: get_needs

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def get_needs(self):
        model_fields = [
            f
            for f in self.model._meta.get_fields()
            if f.is_relation and f.name in self.get_fields_for_serializer() and (
                not isinstance(f, ForeignKey) or
                self.foreign_key_as_list is False or (
                   isinstance(self.foreign_key_as_list, Iterable) and
                   f.name not in self.foreign_key_as_list
                )
            )
        ]
        related_models = [
            f.related_model
            if f.related_model and f.related_model != self.model
            else f.model if f.model and f.model != self.model else None
            for f in model_fields
        ]
        return [
            {
                'app': model._meta.app_label,
                'singular': model._meta.model_name.lower(),
                'plural': self.inflector.pluralize(model._meta.model_name.lower()),
            } for model in related_models if model is not None
        ] 
开发者ID:drf-forms,项目名称:drf-schema-adapter,代码行数:27,代码来源:endpoints.py

示例7: to_dict

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
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 
开发者ID:respawner,项目名称:peering-manager,代码行数:35,代码来源:models.py

示例8: check

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def check(self, **kwargs):
        from modelcluster.models import ClusterableModel

        errors = super(ParentalKey, self).check(**kwargs)

        # Check that the destination model is a subclass of ClusterableModel.
        # If self.rel.to is a string at this point, it means that Django has been unable
        # to resolve it as a model name; if so, skip this test so that Django's own
        # system checks can report the appropriate error
        if isinstance(self.remote_field.model, type) and not issubclass(self.remote_field.model, ClusterableModel):
            errors.append(
                checks.Error(
                    'ParentalKey must point to a subclass of ClusterableModel.',
                    hint='Change {model_name} into a ClusterableModel or use a ForeignKey instead.'.format(
                        model_name=self.remote_field.model._meta.app_label + '.' + self.remote_field.model.__name__,
                    ),
                    obj=self,
                    id='modelcluster.E001',
                )
            )

        # ParentalKeys must have an accessor name (#49)
        if self.remote_field.get_accessor_name() == '+':
            errors.append(
                checks.Error(
                    "related_name='+' is not allowed on ParentalKey fields",
                    hint="Either change it to a valid name or remove it",
                    obj=self,
                    id='modelcluster.E002',
                )
            )

        return errors 
开发者ID:wagtail,项目名称:django-modelcluster,代码行数:35,代码来源:fields.py

示例9: _model_to_dict

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
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 
开发者ID:LPgenerator,项目名称:django-db-mailer,代码行数:17,代码来源:mail.py

示例10: test_no_index_for_foreignkey

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def test_no_index_for_foreignkey(self):
        """
        MySQL on InnoDB already creates indexes automatically for foreign keys.
        (#14180). An index should be created if db_constraint=False (#26171).
        """
        storage = connection.introspection.get_storage_engine(
            connection.cursor(), ArticleTranslation._meta.db_table
        )
        if storage != "InnoDB":
            self.skip("This test only applies to the InnoDB storage engine")
        index_sql = connection.schema_editor()._model_indexes_sql(ArticleTranslation)
        self.assertEqual(index_sql, [
            'CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` '
            'ON `indexes_articletranslation` (`article_no_constraint_id`)'
        ])

        # The index also shouldn't be created if the ForeignKey is added after
        # the model was created.
        field_created = False
        try:
            with connection.schema_editor() as editor:
                new_field = ForeignKey(Article, CASCADE)
                new_field.set_attributes_from_name('new_foreign_key')
                editor.add_field(ArticleTranslation, new_field)
                field_created = True
                self.assertEqual(editor.deferred_sql, [
                    'ALTER TABLE `indexes_articletranslation` '
                    'ADD CONSTRAINT `indexes_articletrans_new_foreign_key_id_d27a9146_fk_indexes_a` '
                    'FOREIGN KEY (`new_foreign_key_id`) REFERENCES `indexes_article` (`id`)'
                ])
        finally:
            if field_created:
                with connection.schema_editor() as editor:
                    editor.remove_field(ArticleTranslation, new_field) 
开发者ID:denisenkom,项目名称:django-sqlserver,代码行数:36,代码来源:tests.py

示例11: serialize_model

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def serialize_model(self):
        """
        Check the fields of models and convert the data

        Returns: Dictionary
        """
        if not hasattr(self.model, '__dict__'):
            raise TypeError("Models or Dictionary is required")
        response = {}
        opts = self.model._meta
        for field in opts.local_fields:
            # for a django model, retrieving a foreignkey field
            # will fail when the field value isn't set
            try:
                value = getattr(self.model, field.name)
            except ObjectDoesNotExist:
                value = None
            if isinstance(value, datetime):
                value = datetime_to_str(value)
            if isinstance(value, timedelta):
                value = timedelta_to_str(value)
            if isinstance(field, ForeignKey):
                fk_id = "%s_id" % field.name
                if value is None:
                    response[fk_id] = None
                else:
                    response[fk_id] = getattr(self.model, fk_id)
                    value = str(value)
            response[field.name] = value
        for field in opts.local_many_to_many:
            value = getattr(self.model, field.name)
            value = value.values_list('pk', flat=True)
            response[field.name] = list(value)
        return response 
开发者ID:kiwitcms,项目名称:Kiwi,代码行数:36,代码来源:serializer.py

示例12: test_no_index_for_foreignkey

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def test_no_index_for_foreignkey(self):
        """
        MySQL on InnoDB already creates indexes automatically for foreign keys.
        (#14180). An index should be created if db_constraint=False (#26171).
        """
        storage = connection.introspection.get_storage_engine(
            connection.cursor(), ArticleTranslation._meta.db_table
        )
        if storage != "InnoDB":
            self.skip("This test only applies to the InnoDB storage engine")
        index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(ArticleTranslation)]
        self.assertEqual(index_sql, [
            'CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` '
            'ON `indexes_articletranslation` (`article_no_constraint_id`)'
        ])

        # The index also shouldn't be created if the ForeignKey is added after
        # the model was created.
        field_created = False
        try:
            with connection.schema_editor() as editor:
                new_field = ForeignKey(Article, CASCADE)
                new_field.set_attributes_from_name('new_foreign_key')
                editor.add_field(ArticleTranslation, new_field)
                field_created = True
                self.assertEqual([str(statement) for statement in editor.deferred_sql], [
                    'ALTER TABLE `indexes_articletranslation` '
                    'ADD CONSTRAINT `indexes_articletrans_new_foreign_key_id_d27a9146_fk_indexes_a` '
                    'FOREIGN KEY (`new_foreign_key_id`) REFERENCES `indexes_article` (`id`)'
                ])
        finally:
            if field_created:
                with connection.schema_editor() as editor:
                    editor.remove_field(ArticleTranslation, new_field) 
开发者ID:nesdis,项目名称:djongo,代码行数:36,代码来源:tests.py

示例13: handle

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def handle(self, *args, **kwargs):
        classes_we_care_about = (VMP, VMPP, AMP, AMPP, GTIN)
        ids = kwargs["ids"]
        objs = []
        for cls in classes_we_care_about:
            objs.extend(cls.objects.filter(id__in=ids))

        for obj in objs:
            for f in obj._meta.get_fields():
                if isinstance(f, ForeignKey):
                    related_obj = getattr(obj, f.name)
                    if related_obj is not None and related_obj not in objs:
                        objs.append(related_obj)

                if (
                    kwargs["include_reverse_relations"]
                    and isinstance(obj, classes_we_care_about)
                    and isinstance(f, ManyToOneRel)
                    and f.related_model in classes_we_care_about
                ):
                    if isinstance(f, OneToOneRel):
                        try:
                            objs.append(getattr(obj, f.get_accessor_name()))
                        except ObjectDoesNotExist:
                            pass
                    else:
                        related_objs = getattr(obj, f.get_accessor_name()).all()
                        for related_obj in related_objs:
                            if related_obj not in objs:
                                objs.append(related_obj)

        print(serializers.serialize("json", objs, indent=2)) 
开发者ID:ebmdatalab,项目名称:openprescribing,代码行数:34,代码来源:generate_dmd_fixture.py

示例14: run_with_model_cls

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def run_with_model_cls(self, model_cls: Type[Model]) -> None:
        for field in model_cls._meta.get_fields():
            if isinstance(field, ForeignKey):
                related_model_cls = self.django_context.get_field_related_model_cls(field)
                if related_model_cls is None:
                    error_context: Context = self.ctx.cls
                    field_sym = self.ctx.cls.info.get(field.name)
                    if field_sym is not None and field_sym.node is not None:
                        error_context = field_sym.node
                    self.api.fail(f'Cannot find model {field.related_model!r} '
                                  f'referenced in field {field.name!r} ',
                                  ctx=error_context)
                    self.add_new_node_to_model_class(field.attname,
                                                     AnyType(TypeOfAny.explicit))
                    continue

                if related_model_cls._meta.abstract:
                    continue

                rel_primary_key_field = self.django_context.get_primary_key_field(related_model_cls)
                try:
                    field_info = self.lookup_class_typeinfo_or_incomplete_defn_error(rel_primary_key_field.__class__)
                except helpers.IncompleteDefnException as exc:
                    if not self.api.final_iteration:
                        raise exc
                    else:
                        continue

                is_nullable = self.django_context.get_field_nullability(field, None)
                set_type, get_type = get_field_descriptor_types(field_info, is_nullable)
                self.add_new_node_to_model_class(field.attname,
                                                 Instance(field_info, [set_type, get_type])) 
开发者ID:typeddjango,项目名称:django-stubs,代码行数:34,代码来源:models.py

示例15: get_field_nullability

# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ForeignKey [as 别名]
def get_field_nullability(self, field: Union[Field, ForeignObjectRel], method: Optional[str]) -> bool:
        nullable = field.null
        if not nullable and isinstance(field, CharField) and field.blank:
            return True
        if method == '__init__':
            if ((isinstance(field, Field) and field.primary_key)
                    or isinstance(field, ForeignKey)):
                return True
        if method == 'create':
            if isinstance(field, AutoField):
                return True
        if isinstance(field, Field) and field.has_default():
            return True
        return nullable 
开发者ID:typeddjango,项目名称:django-stubs,代码行数:16,代码来源:context.py


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