I’m getting an error when I try to save a model that has a foreign key. The app name is “Music”. My models.
class Event(models.Model):
eventUrl = models.URLField('url', primary_key=True)
eventTime = models.DateTimeField('date and time')
location = models.CharField('location/venue',max_length='75')
title = models.CharField('title',max_length='255')
def __unicode__(self):
return self.eventUrl
class Performer(models.Model):
url = models.ForeignKey(Event)
performer = models.CharField('performer', max_length='75')
instrument = models.CharField('instrument or ensemble', max_length='75')
def __unicode__(self):
return self.performer
The Tables that are generated
class MusicEvent(models.Model):
eventurl = models.CharField(max_length=200, primary_key=True, db_column=u'eventUrl') # Field name made lowercase.
eventtime = models.DateTimeField(db_column=u'eventTime') # Field name made lowercase.
location = models.CharField(max_length=75)
title = models.CharField(max_length=255)
class Meta:
db_table = u'music_event'
class MusicPerformer(models.Model):
id = models.IntegerField(primary_key=True)
performer = models.CharField(max_length=75)
class Meta:
db_table = u'music_performer'
class MusicPerformerEventurl(models.Model):
id = models.IntegerField(primary_key=True)
performer_id = models.IntegerField()
event = models.ForeignKey(MusicEvent)
class Meta:
db_table = u'music_performer_eventUrl'
The code in my view
p = Performer(url=e,performer=name,instrument=inst)
p.save()
I get the following error
Request Method: POST
Request URL: http://127.0.0.1:8000/events/import_data/
Django Version: 1.3.1
Exception Type: DatabaseError
Exception Value:
table music_performer has no column named url_id
Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 234
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.2
So it seems to say that the table doesn’t have the column url, which is the foreign key. Why is it that it didn’t generate that as a column, even though it’s in my model? How do I assign the “event” foreign key to the new performer object?
I didn’t realize that “flush” doesn’t drop the tables, and “sync” doesn’t alter existing tables. I fixed this issue by manually dropping the tables in the shell and running “sync” again. What is the “standard” to update tables when you alter models (adding or changing names of existing fields?)