How to import Fixture in Django with Sqlite with Foreign Key disabled

Questo articolo è stato scritto oltre 1 years, il contenuto potrebbe essere datato.

You have various fixtures but maybe they are referenced between each other so they in the import don’t exists.

This is a pain but with a custom django command to put in `your-app/management/commands` you can disable that check in Sqlite and proceed!

This is the code:

from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import connection


class Command(BaseCommand):
    help = 'Import fixture disable the Foreign Key check'

    def add_arguments(self, parser):
        parser.add_argument('fixture', nargs='+', type=str, help='Fixture files')

    def handle(self, *args, **kwargs):
        fixture_files = kwargs['fixture']

        with connection.cursor() as cursor:
            cursor.execute('PRAGMA foreign_keys = OFF;')

        try:
            for fixture in fixture_files:
                call_command('loaddata', fixture)
        except Exception as e:
            self.stderr.write(f"Error on loading the fixture: {e}")
        finally:
            # Riabilita i vincoli FK
            with connection.cursor() as cursor:
                cursor.execute('PRAGMA foreign_keys = ON;')

You can use `loaddata_fk` as alternative for `loaddata`, in this way you are able to import what you need.

 

Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *