Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - How to prevent database foreign key constraint creation
    text
    copied!<p>I have a model that is backed by a database view.</p> <pre><code>class OrgCode(models.Model): org_code = models.CharField(db_column=u'code',max_length=15) org_description = models.CharField(max_length=250) org_level_num = models.IntegerField() class Meta: db_table = u'view_FSS_ORG_PROFILE' </code></pre> <p>I need to reference this in another model</p> <pre><code>class AssessmentLocation(models.Model): name = models.CharField(max_length=150) org = models.ForeignKey(OrgCode) </code></pre> <p>I can't run syncdb because foreign key constraints cannot be created referencing a view.</p> <pre><code> u"Foreign key 'FK__main_asse__org__1D114BD1' references object 'view_FSS_ORG_PROFILE' which is not a user table.", None, 0, -214 7217900), None) Command: CREATE TABLE [main_assessmentlocation] ( [id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY, [name] nvarchar(150) NOT NULL, [org] int NOT NULL REFERENCES [view_FSS_ORG_PROFILE] ([id]), ) </code></pre> <p>The workaround is to take out the Meta:db_table pointing to the view and let sync db create the the OrgCode table, then put the Meta:db_table back in after syncdb. </p> <p>Is there a way to prevent the creation of foreign key constraints for certain models or fields?</p> <p><strong>Update:</strong> I added a static method to the related model indicating it's a view</p> <pre><code>class OrgCode(models.Model): org_code = models.CharField(max_length=15) org_description = models.CharField(max_length=250) @staticmethod def is_backend_view(): return True </code></pre> <p>Then overrode DatabaseCreation.sql_for_inline_foreign_key_references in django_mssql creation.py:</p> <pre><code>def sql_for_inline_foreign_key_references(self, field, known_models, style): try: field.rel.to.is_backend_view() return "", False except: return super(DatabaseCreation,self).sql_for_inline_foreign_key_references(field, known_models, style) </code></pre> <p>The generated sql from syncdb leaves out the constraint:</p> <pre><code>CREATE TABLE [main_assessmentlocation] ( [id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY, [name] nvarchar(150) NOT NULL, [org] int, -- NO FK CONSTRAINT ANYMORE -- ); </code></pre> <p>It does involve hacking django_mssql so I'm going to keep on trying, maybe hooking into the django.db.backends.signals.connection_created signal will work...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload