mypebble / django-pgviews

Fork of django-postgres that focuses on maintaining and improving support for Postgres SQL Views.
The Unlicense
195 stars 41 forks source link

id Column does not exist #33

Open awgymer opened 6 years ago

awgymer commented 6 years ago

I am trying to use a MaterializedView to hold some aggregated queries from one of my model tables. Everything seems fine, however when I try to use the result like a queryset calling MyView.objects.all() I get the error column per_machine.id does not exist. It seems that django expects an id column to always be present but that unlike a normal model, and AutoField isn't assigned by default. Is this just the expected behaviour and if so is the intention that one should specify an explicit id column or am I simply misusing the resulting queryset by calling objects.all()?

scott-w commented 6 years ago

Hi @datchpenguin, thanks for this.

Django does depend on an id field existing. This can be in a couple of ways:

  1. Set one of your fields to primary_key=True - this will map .id to that field
  2. Generate an id field in your view SQL that Django can use to uniquely identify
  3. Set a generic value like 1 AS id in your SQL if you're not interested in the ID field

Usually, it's considered good to determine a primary key for your view so you can look it up, in which case, 1 or 2 would be needed. If you never use a primary key, then just do 3 and that should work fine for most cases.

awgymer commented 6 years ago

Thanks for the speedy reply. Yes, I expected (1) was going to be the solution but I'm clearly too used to letting Django create an automatic id field for my models.

scott-w commented 6 years ago

Hi @datchpenguin no worries. If you'd like to open a PR to update the README, I'd be more than happy to include the information :)