简体   繁体   中英

How do I fix table x has no column named y?

I edited a model in django and as a result I get the error: "table reserve_time has no column named reservation" for the below models:

from django.db import models
import datetime

class Club(models.Model):
    establishment = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    def __unicode__(self):
        return self.establishment

class Day(models.Model):
    club = models.ForeignKey(Club)
    day = models.DateField('day')
    def __unicode__(self):
        return unicode(self.day)

class Court(models.Model):
    club = models.ForeignKey(Club)
    day = models.ForeignKey(Day)
    court = models.IntegerField(max_length=200)
    def __unicode__(self):
        return unicode(self.court)

class Time(models.Model):
    club = models.ForeignKey(Club)
    day = models.ForeignKey(Day)
    court = models.ForeignKey(Court)
    time = models.TimeField('time')
    reservation = models.CharField(max_length=200)
    def __unicode__(self):
        return unicode(self.time)

I ran python manage.py syncdb and python manage.py runserver after, but I still get the above error. Any ideas on how to fix this? If I remove the "reservation" field, it works fine. In the admin, the textbox for "reservation" appears but the error comes up when I try save.

The problem here is that django will not do anything to fix your tables when you make field changes. All syncdb will do is create tables that do not already exist. If you decide to change your schema and add fields, you either need to create them manually in your database, or drop the table and let syncdb recreate it, or start using a project like South to handle database migrations.

The reason this cannot work is because you would already theoretically have existing records in the table, and there is no sure way to know what you do with all those missing fields. Maybe these fields cannot be null. Maybe they have other constraints that must be satisfied. Apparently South can manage this situation.

Update (Dec. 2019)

It has been over 7 years since I have used django, but it seems that nowadays the database migration functionality has been integrated as a first class concept: https://docs.djangoproject.com/en/3.0/topics/migrations/

Syncdb does not alter existing models dbwise. One possibility is to manually edit your db, or delete the model from your db and run syncdb again (shouldn't be done in a productive environment without proper backup).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM