Django:" Soft"没有数据库完整性检查的ForeignField

时间:2012-05-16 17:45:36

标签: database django-models foreign-keys constraints

我有一个Django项目,有多个django“应用程序”。其中一个模型表示来自外部源的数据(我不控制这些数据)。

我希望我的其他应用程序能够引用此“外部应用程序”,但我想避免数据库完整性检查的所有模糊。我不希望db对这些“软外键”有任何限制。

你知道如何编写一个自定义字段来模拟真正的Django ForeignKey而不在数据库上创建硬约束吗?

也许这已经存在,但我在谷歌上没有运气。

提前感谢您的帮助: - )

注意:我知道带有content_types的generic relations系统。但我不想要通用关系。我希望只与没有严格完整性约束的特定模型建立特定关系。

编辑:

我找到了相关链接:

但我没有找到适合我问题的答案。 :(

2012年6月4日编辑:

我深入研究了django的代码以找到需要做的事情,但我认为简单地继承ForeignKey是不够的。你能告诉我一些如何做的指示吗?

注意:我使用South来管理我的数据库架构,所以我想我也需要对此做些什么。但这可能超出了主题:)

6 个答案:

答案 0 :(得分:3)

哟伙计们,

我设法做出我想要的东西。

首先,我创建了一个新字段:

from django.db.models.deletion import DO_NOTHING
from django.db.models.fields.related import ForeignKey, ManyToOneRel

class SoftForeignKey(ForeignKey):
    """
    This field behaves like a normal django ForeignKey only without hard database constraints.
    """
    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

    no_db_constraints = True

由于我使用South来管理我的数据库架构,我不得不添加:

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], [r'^ecm\.lib\.softfk\.SoftForeignKey'])

然后,我不得不向南试图补丁,以便考虑no_db_constraints参数。创建FK约束涉及两个函数:

from django.db.models.deletion import DO_NOTHING
from django.db.models.fields.related import ForeignKey, ManyToOneRel
from django.core.management.color import no_style
from south.db.generic import DatabaseOperations, invalidate_table_constraints, flatten

def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False):
    """
    Creates the SQL snippet for a column. Used by add_column and add_table.
    """

    # If the field hasn't already been told its attribute name, do so.
...
...
...

        if field.rel and self.supports_foreign_keys:
            # HACK: "soft" FK handling begin
            if not hasattr(field, 'no_db_constraints') or not field.no_db_constraints:
                self.add_deferred_sql(
                    self.foreign_key_sql(
                        table_name,
                        field.column,
                        field.rel.to._meta.db_table,
                        field.rel.to._meta.get_field(field.rel.field_name).column
                    )
                )
            # HACK: "soft" FK handling end

    # Things like the contrib.gis module fields have this in 1.1 and below
    if hasattr(field, 'post_create_sql'):
        for stmt in field.post_create_sql(no_style(), ta
....
....

# monkey patch South here
DatabaseOperations.column_sql = column_sql

from django.db.models.deletion import DO_NOTHING
from django.db.models.fields.related import ForeignKey, ManyToOneRel
from django.core.management.color import no_style
from south.db.generic import DatabaseOperations, invalidate_table_constraints, flatten

@invalidate_table_constraints
def alter_column(self, table_name, name, field, explicit_name=True, ignore_constraints=False):
    """
    Alters the given column name so it will match the given field.
    Note that conversion between the two by the database must be possible.
    Will not automatically add _id by default; to have this behavour, pass
    explicit_name=False.

    @param table_name: The name of the table to add the column to
    @param name: The name of the column to alter
    @param field: The new field definition to use
    """

    if self.dry_run:
        if self.debug:
...
...
    if not ignore_constraints:
        # Add back FK constraints if needed
        if field.rel and self.supports_foreign_keys:
            # HACK: "soft" FK handling begin
            if not hasattr(field, 'no_db_constraints') or not field.no_db_constraints:
                self.execute(
                    self.foreign_key_sql(
                        table_name,
                        field.column,
                        field.rel.to._meta.db_table,
                        field.rel.to._meta.get_field(field.rel.field_name).column
                    )
                )
            # HACK: "soft" FK handling end

# monkey patch South here
DatabaseOperations.alter_column = alter_column

这真的很丑,但我没有找到另一种方式。

现在您可以使用SoftForeignKey字段,就像普通的ForeignKey一样,但您不会执行任何参照完整性。

请参阅此处查看完整的猴子补丁:http://eve-corp-management.org/projects/ecm/repository/entry/ecm/lib/softfk.py

答案 1 :(得分:3)

如果您只想禁用字段上的ForeignKey约束检查,则只需将db_constraint=False添加到该字段。

user = models.ForeignKey('User', db_constraint=False)

另见: Django - How to prevent database foreign key constraint creation

答案 2 :(得分:2)

我尝试了类似于Izz ad-Din Ruhulessin的建议,但它没有用,因为我有除“假FK”专栏以外的专栏。我试过的代码是:

class DynamicPkg(models.Model):
    @property
    def cities(self):
        return City.objects.filter(dpdestinations__dynamic_pkg=self)


class DynamicPkgDestination(models.Model):
    dynamic_pkg = models.ForeignKey(DynamicPkg, related_name='destinations')
    # Indexed because we will be joining City.code to
    # DynamicPkgDestination.city_code and we want this to be fast.
    city_code = models.CharField(max_length=10, db_index=True)


class UnmanagedDynamicPkgDestination(models.Model):
    dynamic_pkg = models.ForeignKey(DynamicPkg, related_name='destinations')
    city = models.ForeignKey('City', db_column='city_code', to_field='code', related_name='dpdestinations')

    class Meta:
        managed = False
        db_table = DynamicPkgDestination._meta.db_table


class City(models.Model):
    code = models.CharField(max_length=10, unique=True)

我得到的错误是:

Error: One or more models did not validate:
travelbox.dynamicpkgdestination: Accessor for field 'dynamic_pkg' clashes with related field 'DynamicPkg.destinations'. Add a related_name argument to the definition for 'dynamic_pkg'.
travelbox.dynamicpkgdestination: Reverse query name for field 'dynamic_pkg' clashes with related field 'DynamicPkg.destinations'. Add a related_name argument to the definition for 'dynamic_pkg'.
travelbox.unmanageddynamicpkgdestination: Accessor for field 'dynamic_pkg' clashes with related field 'DynamicPkg.destinations'. Add a related_name argument to the definition for 'dynamic_pkg'.
travelbox.unmanageddynamicpkgdestination: Reverse query name for field 'dynamic_pkg' clashes with related field 'DynamicPkg.destinations'. Add a related_name argument to the definition for 'dynamic_pkg'.

然而,我确实通过使用代理模型提出了一个有效的解决方案。我仍然需要破解一些Django验证,以防止字段被包含在代理模型中:

class DynamicPkg(models.Model):
    @property
    def cities(self):
        return City.objects.filter(dpdestinations__dynamic_pkg=self)



def proxify_model(new_class, base):
    """
    Like putting proxy = True in a model's Meta except it doesn't spoil your
    fun by raising an error if new_class contains model fields.
    """
    new_class._meta.proxy = True
    # Next 2 lines are what django.db.models.base.ModelBase.__new__ does when
    # proxy = True (after it has done its spoil-sport validation ;-)
    new_class._meta.setup_proxy(base)
    new_class._meta.concrete_model = base._meta.concrete_model


class DynamicPkgDestination(models.Model):
    dynamic_pkg = models.ForeignKey(DynamicPkg, related_name='destinations')
    # Indexed because we will be joining City.code to
    # DynamicPkgDestination.city_code and we want this to be fast.
    city_code = city_code_field(db_index=True)


class ProxyDynamicPkgDestination(DynamicPkgDestination):
    city = models.ForeignKey('City', db_column='city_code', to_field='code', related_name='dpdestinations')


proxify_model(ProxyDynamicPkgDestination, DynamicPkgDestination)


class City(models.Model):
    code = models.CharField(max_length=10, unique=True)

答案 3 :(得分:1)

您可以尝试使用非托管模型:

from django.db import models


class ReferencedModel(models.Model):
    pass


class ManagedModel(models.Model):
    my_fake_fk = models.IntegerField(
        db_column='referenced_model_id'
    )


class UnmanagedModel(models.Model):
    my_fake_fk = models.ForeignKey(
        ReferencedModel, 
        db_column='referenced_model_id'
    )

    class Meta:
        managed = False
        db_table = ManagedModel._meta.db_table

在Model Meta类中指定managed=False不会为其创建db表。但是,它的行为与其他模型完全相同。

答案 4 :(得分:1)

背诵marianobianchi的评论,ForeignKey.on_delete的选项之一是

  

DO_NOTHING:不采取任何行动。如果数据库后端强制实施参照完整性,除非您手动将SQL ON DELETE约束添加到数据库字段(可能使用初始sql),否则这将导致IntegrityError。

这与在数据库级别禁用外键约束相结合应该可以解决问题。据我所知,有两种方法可以做到这一点。您可以完全禁用fk约束:

from django.db.backend.signals import connection_created
from django.dispatch import receiver

@receiver(connection_created)
def disable_constraints(sender, connection):
    connection.disable_constraint_checking()

看起来django db后端也提供了一个constraint_checks_disabled上下文管理器,所以你可以在这样的代码中包装相关的db访问,以避免在整个过程中禁用检查:

from django.db import connection
with connection.constraint_checks_disabled():
    do_stuff()

答案 5 :(得分:0)

I solved this by using a GenericForeignKey:

thing_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
thing_object_id = models.UUIDField(default=uuid.uuid4, blank=True, null=True)

thing = GenericForeignKey(ct_field='thing_content_type', fk_field='thing_object_id')

On the plus side, it's out-of-the-box Django

On the negative side, you have three additional attributes in your model.

Additionally, reverse relations don't automatically work, but in my case, I'm okay with that.