-
Notifications
You must be signed in to change notification settings - Fork 41
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
Ability to use fields from related models for defining for conditions #47
Comments
Have not tested this, but as a workaround, try a |
Works wonders! Thanks for the suggestions @MarkKoz ! Here's a made-up script for anyone looking at similar requirement: We are trying to ensure that the City has same Country as that assigned to State. i.e. class State(models.Model):
country = models.ForeignKey(Country)
class Meta:
db_table = 'myapp_state'
@pgtrigger.register(
pgtrigger.Trigger(
name='ensure_same_country',
when=pgtrigger.Before,
operation=pgtrigger.Insert | pgtrigger.Update,
func=f"""
DECLARE
country_id INTEGER;
BEGIN
SELECT t.country_id INTO country_id FROM myapp_state as t WHERE t.id=NEW.country_id LIMIT 1;
IF country_id != NEW.country_id THEN
RAISE EXCEPTION 'invalid country_id: country being inserted is "%" which is not equal to country assigned to strategy_task(%) %', NEW.country_id, NEW.state_id, country_id;
END IF;
RETURN NEW;
END;""",
)
)
class City(models.Model):
country = models.ForeignKey(Country)
state = models.ForeignKey(State) |
@tiholic thanks for showing the example! Unfortunately it's not possible to do that type of condition with Postgres trigger conditions. Trigger conditions can only be defined on table columns and cannot do joins. I'm going to mark this as a wontfix. I'm going re-open this issue for now and close it after I:
|
Here's an example representation of my models:
And I wanted to make sure
tag.user
is same asactivity.user
. So I added the following trigger onTagBinding
classAd when running
./manage.py pgtrigger install
, it throws:Tried dropping the
_id
fromuser_id
from bothF
statement andQ
statement. No luck.Is there any way to work around this?
I mainly want to use triggers to ensure that my related data belongs to same user (tried using constraints, but they cannot be configured on related models, so I read that triggers are the solution, but the above errors put a question mark on this approach). Should I do application level validation instead? Please suggest on what can be done here @wesleykendall :)
The text was updated successfully, but these errors were encountered: