Search code examples
djangodelete-rowsql-view

In Django, cannot delete model instance because of FK in second (and view-based) model


I defined in Django two models, the second one is based on the first, and is not managed because it is based backend on a SQL Server view (not on a table)

class Embedder(models.Model):
  {my_fields...}

class MostRecent(models.Model):
  embedder = models.ForeignKey(Embedder)
  status = models.IntegerField()

  class Meta:
    db_table = 'embedder_most_recent'
    managed = False

The problem is that I can't delete an instance of Embedder because of this error:

View or function 'embedder_most_recent' is not updatable because the modification affects multiple base tables. (4405) (SQLExecDirectW)")

The problem seems to reside in Django since I can delete the embedder row in SQL without error. How can I solve the problem?


Solution

  • As marcusshep already posted, there is sufficient documentation for this behavior in the Django docs.

    Since a Django ForeignKey references another Django model object, any attempt to delete the parent object means Django must find a way to manage objects referencing the ForeignKey. You should specify this behavior explicitly.

    The example below will delete the object containing the ForeignKey:

    class MostRecent(models.Model):
       embedder = models.ForeignKey(Embedder, on_delete=models.CASCADE)
       status = models.IntegerField()