How can I load circular foreign key devices in django?

I have a model for categories that contains a circular foreign key. I dumped all the data from this model, and I created data migration using django-south to load it into another DBMS, but I have a lot of problems with this because of this circular dependency.

This is the model I'm talking about:

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') 
+4
source share
3 answers

Thanks to this post, I was able to find a solution. Temporarily disabling foreign key verification when loading data is the best possible solution to solve these problems. Since Django does not provide a way to do this, we must execute raw sql code. So, I created data migration using django-south, and the rest is in the code below:

 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() 
+11
source

Quick answer: you need to disable foreign key constraints at boot time.

There is a patch for Django, but it may or may not be in the version you are using:

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


Alternatively, do not use appliances, use SQL: https://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data

The good news is that you can do anything in a model SQL file that you can do in SQL. The downside is that it is no longer aggregated for the database, depending on the SQL you are using.

+3
source

Answered in 2016. Django supports loading interdependent devices, just adding them to the same file

 // fixtures.json [ { "model": "A", "pk": 1100, "fields": { "bfk": 1000, } }, { "model": "B", "pk": 1000, "fields": { "Afk": 1100 } } ] 
0
source

Source: https://habr.com/ru/post/1380114/


All Articles