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


Python related.ForeignKey类代码示例

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


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

示例1: test_fk

 def test_fk(self):
     "Tests that creating tables out of FK order, then repointing, works"
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Book)
         editor.create_model(Author)
         editor.create_model(Tag)
     # Check that initial tables are there
     list(Author.objects.all())
     list(Book.objects.all())
     # Make sure the FK constraint is present
     with self.assertRaises(IntegrityError):
         Book.objects.create(
             author_id=1,
             title="Much Ado About Foreign Keys",
             pub_date=datetime.datetime.now(),
         )
     # Repoint the FK constraint
     new_field = ForeignKey(Tag)
     new_field.set_attributes_from_name("author")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Book,
             Book._meta.get_field_by_name("author")[0],
             new_field,
             strict=True,
         )
     # Make sure the new FK constraint is present
     constraints = self.get_constraints(Book._meta.db_table)
     for name, details in constraints.items():
         if details['columns'] == ["author_id"] and details['foreign_key']:
             self.assertEqual(details['foreign_key'], ('schema_tag', 'id'))
             break
     else:
         self.fail("No FK constraint for author_id found")
开发者ID:DasAllFolks,项目名称:django,代码行数:35,代码来源:tests.py

示例2: test_no_index_for_foreignkey

    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.
        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)
            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`)'
            ])
开发者ID:japrogramer,项目名称:django,代码行数:27,代码来源:tests.py

示例3: test_no_index_for_foreignkey

    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
                # No deferred SQL. The FK constraint is included in the
                # statement to add the field.
                self.assertFalse(editor.deferred_sql)
        finally:
            if field_created:
                with connection.schema_editor() as editor:
                    editor.remove_field(ArticleTranslation, new_field)
开发者ID:EmadMokhtar,项目名称:django,代码行数:32,代码来源:tests.py

示例4: __init__

 def __init__(self, to, chained_field=None, chained_model_field=None, show_all=False, auto_choose=False, **kwargs):
     if isinstance(to, basestring):
         self.app_name, self.model_name = to.split('.')
     else:
         self.app_name = to._meta.app_label
         self.model_name = to._meta.object_name
     self.chain_field = chained_field
     self.model_field = chained_model_field
     self.show_all = show_all
     self.auto_choose = auto_choose
     ForeignKey.__init__(self, to, **kwargs)
开发者ID:Anber,项目名称:django-smart-selects,代码行数:11,代码来源:db_fields.py

示例5: test_fk_index_creation

 def test_fk_index_creation(self):
     new_field = ForeignKey(Foo)
     new_field.set_attributes_from_name(None)
     with connection.schema_editor() as editor:
         editor.add_field(
             Bar,
             new_field
         )
         # Just return indexes others that not automaically created by Fk
         indexes = editor._get_field_indexes(Bar, new_field)
     self.assertEqual(indexes, [])
开发者ID:maxirobaina,项目名称:django-firebird,代码行数:11,代码来源:tests.py

示例6: _register

def _register(model, field_name, related_name, model_registry, model_map):
    """ Set up the foreign keys on the `Action` model """
    if model in model_registry:
        return
    
    model_registry.append(model)
    
    field = ForeignKey(model, related_name=related_name, blank=True, null=True,
        db_index=True)
    field.contribute_to_class(Action, field_name)
    
    model_map[model] = [related_name, field_name]
开发者ID:Asinox,项目名称:django-stream,代码行数:12,代码来源:utils.py

示例7: __init__

    def __init__(self, to, address_field=None, **kwargs):

        if isinstance(to, six.string_types):
            self.app_name, self.model_name = to.split('.')
        else:
            self.app_name = to._meta.app_label
            self.model_name = to._meta.object_name

        self.address_field = address_field
        kwargs.setdefault('blank', True)
        kwargs.setdefault('null', True)

        ForeignKey.__init__(self, to, **kwargs)
开发者ID:SergeyTsaplin,项目名称:django-fias,代码行数:13,代码来源:address.py

示例8: __init__

 def __init__(self, to, chained_field=None, chained_model_field=None,
              show_all=False, auto_choose=False, view_name=None, exclude_self=None, **kwargs):
     if isinstance(to, basestring):
         self.app_name, self.model_name = to.split('.')
     else:
         self.app_name = to._meta.app_label
         self.model_name = to._meta.object_name
     self.chain_field = chained_field
     self.model_field = chained_model_field
     self.show_all = show_all
     self.auto_choose = auto_choose
     self.view_name = view_name
     ForeignKey.__init__(self, to, **kwargs)
     self.exclude_self = exclude_self
     #TODO: clean-up
     if exclude_self:
         self.exclude_self = exclude_self
开发者ID:zhangguiyu,项目名称:django-smart-selects,代码行数:17,代码来源:db_fields.py

示例9: __init__

    def __init__(self, to, chained_field=None, chained_model_field=None,
                 show_all=False, auto_choose=False, view_name=None, **kwargs):
        """
        examples:

        class Continent(models.Model):
            name = models.CharField(max_length=255)

        class Country(models.Model):
            continent = models.ForeignKey(Continent)

        class Location(models.Model):
            continent = models.ForeignKey(Continent)
            country = ChainedForeignKey(
                Country,
                chained_field="continent",
                chained_model_field="continent",
                show_all=True,
                auto_choose=True,
                # limit_choices_to={'name':'test'}
            )
        ``chained_field`` is the name of the ForeignKey field referenced by ChainedForeignKey of the same Model.
        in the examples, chained_field is the name of field continent in Model Location.

        ``chained_model_field`` is the name of the ForeignKey field referenced in the 'to' Model.
        in the examples, chained_model_field is the name of field continent in Model Country.

        ``show_all`` controls whether show other choices below the filtered choices, with separater '----------'.

        ``auto_choose`` controls whether auto select the choice when there is only one available choice.

        ``view_name`` controls which view to use, 'chained_filter' or 'chained_filter_all'.

        """
        if isinstance(to, six.string_types):
            self.to_app_name, self.to_model_name = to.split('.')
        else:
            self.to_app_name = to._meta.app_label
            self.to_model_name = to._meta.object_name
        self.chained_field = chained_field
        self.chained_model_field = chained_model_field
        self.show_all = show_all
        self.auto_choose = auto_choose
        self.view_name = view_name
        ForeignKey.__init__(self, to, **kwargs)
开发者ID:DjangoBD,项目名称:django-smart-selects,代码行数:45,代码来源:db_fields.py

示例10: register

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.module_name
    
    if not related_name:
        related_name = 'follow_%s' % model._meta.module_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:teferi,项目名称:django-follow,代码行数:22,代码来源:utils.py

示例11: __init__

 def __init__(self, to, group_field, **kwargs):
     self.group_field = group_field
     self._choices = True
     ForeignKey.__init__(self, to, **kwargs)
开发者ID:SmartgreenSA,项目名称:django-smart-selects,代码行数:4,代码来源:db_fields.py

示例12: __init__

 def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
     ForeignKey.__init__(self, to, to_field=to_field, rel_class=rel_class, **kwargs)
     self.on_delete = DO_NOTHING
开发者ID:Betriebsrat,项目名称:ecm,代码行数:3,代码来源:softfk.py

示例13: __init__

 def __init__(self, to, chained_field, chained_model_field, *args, **kwargs):
     self.app_name = to._meta.app_label
     self.model_name = to._meta.object_name
     self.chain_field = chained_field
     self.model_field = chained_model_field
     ForeignKey.__init__(self, to, *args, **kwargs)
开发者ID:Entropius,项目名称:recordbook,代码行数:6,代码来源:db_fields.py

示例14: __init__

 def __init__(self, translated_field, language, to, to_field=None, *args,
              **kwargs):
     self._related_pre_init(translated_field, language, *args, **kwargs)
     ForeignKey.__init__(self, to, to_field, **kwargs)
     self._related_post_init()
开发者ID:kellycreativetech,项目名称:django-modeltranslation,代码行数:5,代码来源:fields.py

示例15: __init__

 def __init__(self, to='fias.AddrObj', **kwargs):
     kwargs.setdefault('related_name', '+')
     ForeignKey.__init__(self, to, **kwargs)
开发者ID:Apocalepse,项目名称:django-fias,代码行数:3,代码来源:address.py


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