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

Add optional ability to generate SQL using classmethod #47

Open adamhaney opened 5 years ago

adamhaney commented 5 years ago

I have a use case where I'm joining several models into a unified View, and I'd like for the view to include all of the fields from all of the tables (and to update automagically if any of the models have new columns added).

It's possible for me to generate the columns for my SELECT query using a list comprehensions and a model's ._meta.get_fields() method, however, this method fails if the models haven't been loaded into Django yet, so I can't just call .format against my SQL string when defining the View class' sql string.

This changeset allows a view to define a class method generate_sql on a view, if that classmethod is present then it is used to get the sql which is used to define the view instead of the class sql property.

scott-w commented 5 years ago

Hey @adamhaney this looks really good! Could you add some docs for this too please?

I did have one question, would it have been easier to just define an sql() property:

@property
def sql(self):
  return '{}'.format(text)

If you can include a use-case in the docs, that would help clarify this case :)

mikicz commented 3 years ago

I needed this, so added it to my fork - see https://github.com/mikicz/django-pgviews and https://pypi.org/project/django-pgviews-redux/.