On 7 heinä, 22:25, Andrei Antoukh <
n...@niwi.be> wrote:
> Hello!
>
> I am writing about the issues:
https://code.djangoproject.com/ticket/13867https://code.djangoproject.com/ticket/18468
I am not sure this is something we want to support. To me a generic
"get_post_sync_sql(connection)" is a better approach. In addition to
comments you could add indexes, constraints and so on in the hook. It
should be called even for non-managed tables. That way you could use
views using the hook. Trivial example:
class UserPostCount(models.Model):
user = models.OneToOneKey(User, primary_key=True,
db_column="user_id", on_delete=models.DO_NOTHING,
related_name='post_count')
post_count = models.IntegerField()
class Meta:
db_table = 'user_post_count_view'
managed = False
def get_post_sync_sql(connection):
if connection.vendor != 'postgresql':
raise NotImplementedError
return [
"""
CREATE OR REPLACE VIEW user_post_count_view AS (
SELECT
user.id AS user_id, count(*) AS post_count
FROM user
JOIN user_posts ON
user.id = user_posts.user_id
);""",
"""
COMMENT ON VIEW user_post_count_view IS 'A trivial view returning
post count for users.';
"""]
There could also be a get_post_flush_sql(connection) hook.
It seems best if the hooks are called in a second pass - that is, the
whole schema is already installed into the DB before running any of
the post_sync SQL.
Why not use the initial SQL files we already have? They are ran every
time after flush - which means they are useless for defining views for
example - and at least I like to keep the SQL together with model
definition. In addition (IIRC) there are some problems with backends
which do not support executing multiple statements in one go. Still,
one can do logic in the hook, while the initial SQL files are flat
files.
- Anssi