Replies: 4 comments
-
Here's a typed version that allows to specify an extra context: class TemplateFunc(pgtrigger.Func):
def __init__(self, func: str, extra_context: dict[str, Any] | None = None) -> None:
super().__init__(func)
self.extra_context = extra_context or {}
def render(self, model: type[models.Model]) -> str:
fields = {field.name: field for field in model._meta.fields}
columns = {field.name: field.column for field in model._meta.fields}
template = Template(self.func)
context = Context({**{"meta": model._meta, "fields": fields, "columns": columns}, **self.extra_context})
return template.render(context) |
Beta Was this translation helpful? Give feedback.
-
@adonig I really like this suggestion! I'm happy to accept this as a PR to One suggestion - I wonder if there's a way to grab these variables for other models. It's common to write a trigger across a few tables. Could also throw in a basic template tag for people that want to write functions over other models:
Not sure if that's totally correct, but I hope it makes sense. |
Beta Was this translation helpful? Give feedback.
-
@wesleykendall I'm glad it turns out to become useful. The template tag sounds like a good idea. It might look like this: from django import template
from django.apps import apps
from django.db.models.options import Options
register = template.Library()
@register.simple_tag(name="meta")
def meta(model_name: str) -> Options:
model = apps.get_model(model_name)
return model._meta |
Beta Was this translation helpful? Give feedback.
-
Revisiting this discussion since there were two PRs (#149, #150) that both attempted to work around trigger definition limitations. CC @joetsoi and @christophehenry for visibility. To summarize:
Let me know if anything else might be useful here, and I will plan on getting this into pgtrigger |
Beta Was this translation helpful? Give feedback.
-
Hi @Opus10! I'm not sure whether this is something that might be interesting to include or mention in the documentation:
It allows you to use Django's template engine to write trigger functions. I had the following use case:
Beta Was this translation helpful? Give feedback.
All reactions