Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional ability to generate SQL using classmethod #47

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

adamhaney
Copy link

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.

There are some cases where it would be nice to generate the SQL of a view, and this isn't possible if the SQL must be defined on the class because not all apps have loaded at that point. This change checks if the View class has defined a 'generate_sql' classmethod and if they have it uses that to get the sql for that view class
@scott-w
Copy link
Contributor

scott-w commented May 17, 2019

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 :)

This setting allows a dev to disable the automatic syncing behavior.
I've encountered a situation in a project's continuous integration where the post migration signal is run before some of
the tables the view refers to have been created/migrated. This only happens on a brand new environment and most
glaringly on test servers that might not even run all the migrations for unit tests.
@mikicz
Copy link

mikicz commented Nov 22, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants