Rob
Rob

Reputation: 3459

django giving cryptic error for foreignkey

I am getting this error for a django model:

ProgrammingError at /admin/notifications/eventtoken/ column notifications_eventtoken.user_id does not exist LINE 1: ...ications_eventtoken" INNER JOIN "users_user" ON ( "notificat... ^ HINT: Perhaps you meant to reference the column "notifications_eventtoken.used_at".

I added a foreign key for user like this:

class EventToken(models.Model):
    token = models.CharField(max_length=255, db_index=True)
    user = models.ForeignKey(User, null=False, blank=False)
    used_at = models.DateTimeField(null=True, blank=True)
    event = models.ForeignKey(Event)

it works when I remove the user field, but breaks otherwise and I can't tell much from the error message.

Upvotes: 1

Views: 2149

Answers (1)

jdero
jdero

Reputation: 1817

It works when I remove the user field.

This is because your database is missing a column that you have programmed in your EventToken class which I'm guessing is inside of notifications/models.py. This is why it is called a ProgrammingError.

There are several ways to solve this:

1. Delete your entire database and sync it again! Not recommended for anything running on production, but for test projects really doesn't hurt much.

2. Use a tool like south or the django migrate app (depending on which django version you're using) to automate adding a table to your database using the manage.py script. Edit: this solution is the most viable as it's quick and adheres to DRY principles when working across multiple development environments.

3a. Manually go into your database using a command line tool and add the missing column. If I haven't made it clear... you're saying "I want to save the user_id" foreign key in this table" while your table is saying back "There is nowhere to save this ID." ...)

3b. Use a database GUI (like PGadmin for postgresql) and add the user_id column to your notifications_eventtoken database table.

4. Delete the user field in the EventToken class! Don't do this, but understand it works because it clears the logical discrepancy.

Upvotes: 2

Related Questions