Django: “Soft” ForeignField without database integrity checks

前端 未结 6 1389
南旧
南旧 2021-02-05 17:05

I have a Django project that has multiple django \"apps\". One of them has models to represent data coming from an external source (I do not control this data).

I want m

6条回答
  •  半阙折子戏
    2021-02-05 17:25

    Piggybacking off of marianobianchi's comment, one of the options for ForeignKey.on_delete is

    DO_NOTHING: Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add a SQL ON DELETE constraint to the database field (perhaps using initial sql).

    This combined with disabling foreign key constraints at the db level should do the trick. From what I can tell, there are two ways of doing this. You could disable fk constraints entirely like this:

    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()
    

    It looks like the django db backends offer a constraint_checks_disabled context manager, too, so you could wrap the relevant db accesses in code like this to avoid disabling the checks throughout:

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

提交回复
热议问题