當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。