代码之家  ›  专栏  ›  技术社区  ›  Leopd

Django ForeignKey不需要引用完整性?

  •  8
  • Leopd  · 技术社区  · 16 年前

    我想建立一个 ForeignKey django模型中的字段,该字段有时指向另一个表。但是我希望可以在这个字段中插入一个id,这个id引用另一个表中可能不存在的条目。因此,如果该行存在于另一个表中,我希望获得ForeignKey关系的所有好处。但如果不是,我希望这只是一个数字。

    这可能吗?这就是泛型关系的意义吗?

    5 回复  |  直到 16 年前
        1
  •  9
  •   furins    6 年前

    这个问题很久以前就有人问过了,但是对于新手来说,现在有一个内置的方法来处理这个问题,就是在ForeignKey上设置db\u constraint=False:

    https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.db_constraint

    customer = models.ForeignKey('Customer', db_constraint=False)
    

    customer = models.ForeignKey('Customer', null=True, blank=True, db_constraint=False) 
    

    在我们不能保证关系以正确的顺序建立的情况下,我们使用这种方法。

        2
  •  3
  •   Matheus Moreira    16 年前

    我是Django的新手,所以我现在不知道它是否提供了您想要的开箱即用。我想到了这样的事情:

    from django.db import models
    
    class YourModel(models.Model):
        my_fk = models.PositiveIntegerField()
    
        def set_fk_obj(self, obj):
            my_fk = obj.id
    
        def get_fk_obj(self):
            if my_fk == None:
                return None
            try:
                obj = YourFkModel.objects.get(pk = self.my_fk)
                return obj
            except YourFkModel.DoesNotExist:
                return None
    

    我不知道你是否使用了contrib管理应用程序。使用PositiveIntegerField而不是ForeignKey,该字段将在管理站点上用文本字段呈现。

        3
  •  3
  •   Glenn Maynard    16 年前

    这可能与声明ForeignKey并创建列而不实际将其声明为外键一样简单。这样,您将得到o.obj\u id,如果对象存在,o.obj将工作,并且——我认为——如果您尝试加载一个实际上不存在的对象(可能是 DoesNotExist ).

    但是,我不认为有任何办法 syncdb 为你做这个。我发现 同步数据库 ALTER TABLE tablename DROP CONSTRAINT fk_constraint_name .

    当然,在删除级联和所有引用完整性检查上,您也必然会失败。

        4
  •  3
  •   Brian    13 年前

    python manage.py schemamigration myapp name_of_migration --empty

    编辑迁移文件,然后运行它:

    def forwards(self, orm):
        db.delete_foreign_key('table_name', 'field_name')
    
    def backwards(self, orm):
        sql = db.foreign_key_sql('table_name', 'field_name', 'foreign_table_name', 'foreign_field_name')
        db.execute(sql)
    

    Source article

        5
  •  1
  •   Pi Delport    16 年前

    (注:如果您解释一下为什么要这样做,可能会有所帮助。或许有更好的方法来解决根本问题。)

    这可能吗?

    这就是泛型关系的意义吗?

    是的,有一部分。

    contenttypes )

    例子:

    class Foo(models.Model):
    
        other_type = models.ForeignKey('contenttypes.ContentType', null=True)
        other_id = models.PositiveIntegerField()
        # Optional accessor, not a stored column
        other = generic.GenericForeignKey('other_type', 'other_id')
    

    other other_type 和 other_id

    表示一个 不是吗 一份推荐信 其他类型 其他\u id 其他 DoesNotExist (或由于id冲突而返回意外对象)。

        6
  •  -1
  •   Rakshith Raksh    6 年前