如何在django中加载带有圆形外键的灯具?

时间:2011-11-08 03:16:38

标签: django django-south

我有一个类别模型,其中包含一个循环外键。我从这个模型中转储了所有数据,并使用django-south创建了一个数据迁移,以便将它们加载到不同的DBMS中,但由于这种循环依赖性,我在执行此操作时遇到了很多问题。

这是我所指的模型:

class Category(MPTTModel):
    name = models.CharField(_('name'), max_length=50, unique=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='categories')
    description = models.TextField(_('description'), blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add = True, default=date.today())
    updated_on = models.DateTimeField(auto_now = True, default=date.today())

    def __unicode__(self):
        return "%s" %(self.name)

    class Meta:
        verbose_name = _('category')
        verbose_name_plural= _('categories')

3 个答案:

答案 0 :(得分:11)

感谢post我能找到解决方案。在加载数据时暂时禁用外键检查是解决此问题的最佳可行解决方案。 由于Django没有提供这样做的方法,我们应该执行原始的sql代码。 因此,我使用django-south创建了一个数据迁移,其余部分在下面的代码中:

class Migration(DataMigration):

    def forwards(self, orm):
        #~ Disable foreign key checks during fixture loading
        from django.db import connections, DEFAULT_DB_ALIAS
        connection = connections[DEFAULT_DB_ALIAS]
        if 'mysql' in connection.settings_dict['ENGINE']:
            cursor = connection.cursor()
            cursor.execute('SET foreign_key_checks = 0')

        #~ Load fixture
        from django.core.management import call_command
        call_command('loaddata', 'categories_fixture.json', verbosity=0)

        #~ Enable foreign key checks after fixture loading
        if 'mysql' in connection.settings_dict['ENGINE']:
            cursor = connection.cursor()
            cursor.execute('SET foreign_key_checks = 1')
        connection.close()

答案 1 :(得分:3)

快速回答是您需要在加载时禁用外键约束。

Django有一个补丁,但它可能会或可能不会出现在你正在使用的版本中:

https://code.djangoproject.com/ticket/3615


或者,不要使用灯具,请使用SQL:https://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data

好处是你可以在模型SQL文件中执行任何可以在SQL中执行的操作。缺点是它不再与数据库无关,取决于您使用的SQL。

答案 2 :(得分:0)

2016年回答.Django支持加载相互依赖的灯具,只需将它们添加到同一个文件中

// fixtures.json
[
{
    "model": "A",
    "pk": 1100,
    "fields": {
        "bfk": 1000,
    }
},
{
    "model": "B",
    "pk": 1000,
    "fields": {
        "Afk": 1100
    }
}
]
相关问题