Django - How to prevent database foreign key constraint creation

后端 未结 2 1946
傲寒
傲寒 2020-12-30 08:44

I have a model that is backed by a database view.

class OrgCode(models.Model):
    org_code                = models.CharField(db_column=u\'code\',max_length=         


        
2条回答
  •  执念已碎
    2020-12-30 09:05

    If you set managed=False (Django docs) in your model's Meta class, Django will not create the table when you run syncdb.

    class AssessmentLocation(models.Model):
        name = models.CharField(max_length=150)
        org  = models.ForeignKey(OrgCode)
    
        class Meta:
            managed = False
    

    Django has a hook to provide initial sql data. We can (ab?)use this to get Django to create the table immediately after running syncdb.

    Create a file myapp/sql/assessmentlocation.sql, containing the create table statement:

    CREATE TABLE [main_assessmentlocation] (
        [id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
        [name] nvarchar(150) NOT NULL,
        [org] int, -- NO FK CONSTRAINT ANYMORE --
    );
    

    If you have other models with foreign keys to the AssessmentLocation model, you may have problems if Django tries to apply the foreign key constraint before executing the custom sql to create the table. Otherwise, I think this approach will work.

提交回复
热议问题