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

ForeignKey in view? #23

Closed ozacas closed 8 years ago

ozacas commented 8 years ago

Hi,

Maybe this is a dumb question, but is it possible to define a pg.View with a ForeignKey in its projection? The reason I ask, is its natural given an model with an IP address in a model (and postgres) to say something like:

select v.*,o.id AS organisation_id from data_visitor v LEFT OUTER JOIN v.source_ip <<= data_network n LEFT OUTER JOIN data_organisation o ON n.organisation_id = o.id

and then say: class VisitorOrganisation(pg.View): projection = ['Visitor.*', models.ForeignKey(...)] sql = ...

but this fails for me under django v1.8 - models.IntegerField in place of the foreign key is an ugly hack, but it works. Perhaps there is a better way to achieve the ability to identify an organisation for a given visitor's IP address using the postgres specific SQL?

scott-w commented 8 years ago

Hi @ozacas,

It should work in theory, however I tend not to use the projection and just define it as a field on the model itself. Django will map it across to the right fields.

As an aside, you might want to add on_delete=models.DO_NOTHING

ozacas commented 8 years ago

Hi Scott,

Thanks for the aside, always good to be reminded ;-)

I did get an exception (RelatedField's are missing an attribute) but your workaround works fine.

thanks for the prompt reply!

scott-w commented 8 years ago

Hi @ozacas, no worries. I'll close this ticket and open one to update the README to make the information more clear.