Error integrating with MySQL view: "Unknown column in 'field list'"

Hello. I am posting here because I could not find any reference or issue regarding integrating with MySQL views , apart from the setting Meta.managed to False . However, since I want my database lifecycle to always be managed outside of Django, I set Meta.managed to False for each model corresponding to a table. I also did this for the model corresponding to the MySQL view, and expected things to work fine. However, when I access this model in code, I get the error Unknown column <> in 'field list' . Note that I ran both makemigrations and migrate before runserver . On inspecting the migrations file, I see this extra field id for that model’s migration, defined as ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), . I understand that since it is not serializable, it is needed only in-memory. However, I believe there is something wrong with the way the ORM is behaving, given the above error. Does anybody have insights into this?

Every model in Django requires a primary key. If one isn’t defined, Django will add it with a field named id.
However, unless you’re using writable views, that primary key really isn’t “needed”.
What we do with our views is assign an arbitrary column as the primary key. We’ve never had a problem when doing that.
See the docs at Model field reference | Django documentation | Django

1 Like

Thank you Ken for explaining that. Mine is indeed a read-only view. I worked around the issue by making a primary key out of a suitable column. But I don’t think I saw an arbitrary column being made the primary key. I assume that Django knows something is a view through the db and not through anything the programmer specifies.

Sorry, I phrased that badly.

What I should have said is that we specify an arbitrary field in our model as being the primary key of the view - even though the view doesn’t have a primary key.

No, actually it doesn’t. Django doesn’t inspect the db during normal operations. It assumes your models provide a sufficiently accurate representation of the table or view being accessed.
Pretty much anything a database can use to respond to an SQL select statement will work the same within Django. Django creates SQL statements in the ORM and sends them to the database. It either works or it doesn’t…

Thank you Ken. I phrased it wrongly as well. I meant to say field instead of column. Yet, it seems to me that the original error indicates a bug (an arbitrary field was not made the primary key), but I don’t know enough.