Question

This is a follow-up question on Delete field from standard Django model. In short: a field can be dynamically deleted from a model that is already created, in this case the field User.email . So field email would be deleted from User without changing the code for User. See code below for example.

I can dynamically delete a a field from a model(1), but that happens when the server starts and is undone when it exists. Since syncdb doesn't require the server to be running, and generally seems to ignore the deletion code (somehow), this approach doesn't prevent the field from appearing in the database(2).

Is there a way to do delete the field from the model (without changing the file it's in, as it's a Django model), in a way that also makes it not appear in the database?

Thanks in advance!

Mark

EDIT: I problem is not that I am deleting the text "m = models.IntegerField()" from the model file and want the field removed from the database. The problem is that I am using the code below to remove a field from a model that has already been declared in another file. I do not think that creating a migration with South for every time I run syncdb is a solution(3).

Additional information:

  • 1) Currently, the code is in models.py, but I suppose Where to put Django startup code? works.
  • 2) I can delete it on post_syncdb signal with custom query, but I hope for something more elegant... Or elegant at all, more accurately.
  • 3) If it even works at all, because obviously syncdb is still seeing the 'removed' field), so I think South would to as it's still somehow there.

This is the code (models.py):

class A(models.Model):
    m = models.IntegerField()

for i, f in enumerate(A._meta.fields):
    if f.name == 'm':
        del A._meta.fields[i]
        break

class B(A):
    n = models.IntegerField()

for i, f in enumerate(B._meta.fields):
    if f.name == 'm':
        del B._meta.fields[i]
        break

EDIT: I checked (with print) and the deletion code is executed on syncdb. It is executed before tables are created

Was it helpful?

Solution

django does a lot of meta class magic and i would guess that the meta class is responsible for defining the database table to back your model. Subsequently just deleting the field is not enough to alter the generated table.

as several people have pointed out, south is the way to deal with these problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top