'How do i temporarily disable db integrity constraints in django - postgresql

I am writing a Django command to seed an existing table,

I need to truncate the table before seeding, but there are foreign key constraints on that table.

because of that, I am getting django.db.utils.IntegrityError while truncating the table,

How do I turn the Foreign Key Checks off temporarily in Django?

I saw SET FOREIGN KEY CHECK = 0 but don't know where to put them :(

The Django Command class:

class Command(BaseCommand):
help = "Command to seed the aws regions"
regions = [
    {
        'name': 'Us East (N. Virginia)',
        'region': 'us-east-1',
    },
    {
        'name': 'US West (Oregon)',
        'region': 'us-west-2',
    },
    {
        'name': 'EU (Ireland)',
        'region': 'eu-west-1',
    },
]
def handle(self, *args, **options):
    self.stdout.write('seeding regions...')

    AwsRegions.objects.all().delete() # this is where i get errors

    for name, region in self.regions:
        self.stdout.write(region)
        AwsRegions.objects.create(name, region)


    self.stdout.write('done seeding regions')


Solution 1:[1]

To disable triggers for all tables (useful when you need to stop it for multiple tables):

SET session_replication_role TO 'replica'

And to restore:

SET session_replication_role TO 'origin'

Solution 2:[2]

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

Credit goes to https://stackoverflow.com/a/11926432/2558400

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roman Tkachuk
Solution 2 Ramast