Mauzzz0
Mauzzz0

Reputation: 105

Django. How to remove a field from objects in the database?

First, field division had choices with list of available divisions with default='No' . Then it ceased to be necessary, i tried just delete field from model, but get django.core.exceptions.FieldError: Unknown field(s) (division) specified for Team. Then i remove choice, default and set division='None' for all objects. I thought if the value is null (None) then the field can be safely removed, but got the same FieldError: Unknown field(s) specified again.

How can I remove a field from a model, If the database already contains objects with specified field?

models.py

class Team(models.Model):
    name = models.CharField("Name", max_length=50, unique=True)
    image = models.ImageField("Logo", upload_to="img/teams",default="img/team.jpg")
    city = models.CharField("City",max_length=30, default="Moscow")
    division = models.CharField("Division", max_length=50, null=True)
    url = models.SlugField(
        max_length=30,
        unique=True)
    def __str__(self):
        return self.name

Upvotes: 1

Views: 1185

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

I tried just delete field from model, but get django.core.exceptions.FieldError: Unknown field(s) (division) specified for Team.

That FieldError is likely because you use Team in a ModelForm, ModelAdmin, ModelSerializer, or something else where you specified that field. For example a ModelForm with:

class TeamForm(forms.ModelForm):
    class Meta:
        model = Team
        #       reference to division ↓
        fields = ['name', 'city', 'division']

You thus should look at the traceback and find out what form, etc. is referencing to that field and update all the referencing items accordingly.

After doing that you can make a migration where division will be removed from the model.

Upvotes: 3

Related Questions