Django报错OperationalError:polls_bands.id列不存在,执行迁移仍未解决
django.db.utils.OperationalError: no such column: polls_bands.id Hey Ethan, let's work through this error together—it's a super common migration gotcha in Django, so we'll walk through the most likely fixes step by step:
First, double-check your
Bandsmodel definition
Django automatically adds anidprimary key field to every model unless you explicitly define a custom primary key (likeband_id = models.AutoField(primary_key=True)). If you recently changed the primary key field name or removed it accidentally, that would cause Django to look for a column that doesn't exist.
Example of a valid model with the defaultidfield:from django.db import models class Bands(models.Model): name = models.CharField(max_length=100) # Django auto-creates an `id` primary key here—no need to define itConfirm migrations were actually applied
Run this command to check the status of yourpollsapp migrations:python manage.py showmigrations pollsLook for an
[X]next to all migration files—if any are unmarked, runpython manage.py migrate pollsto apply the missing migrations specifically to thepollsapp.Reset stale or missing migration files
Sometimesmakemigrationsfails to generate a migration for subtle changes, or old migrations can get out of sync. If you don't have critical data in your database (or you've backed it up), try:- Delete all files in
polls/migrations/except__init__.py - Re-generate and apply migrations:
python manage.py makemigrations polls python manage.py migrate polls
- Delete all files in
Check for manual database edits
If you modified thepolls_bandstable directly via SQL (instead of using Django migrations), the database and your model definitions will be out of sync. Avoid manual DB edits whenever possible, but if you did, back up any important data, drop thepolls_bandstable, then re-run migrations to rebuild it.Verify app and model naming
Make sure your app is listed aspollsinINSTALLED_APPSinsettings.py, and your model is correctly namedBandsinpolls/models.py. Typos here can lead Django to look for a non-existent table or column.
If none of these resolve the issue, share your full Bands model code and the output of python manage.py showmigrations polls—that'll help us dig deeper.
内容的提问来源于stack exchange,提问作者Ethan Pearce

