Django - How to prevent database foreign key constraint creation

China☆狼群 提交于 2019-11-30 13:37:19

django development version has a db_constraint field for ForeignKey model field - docs.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!