Skip to content

Ability to use fields from related models for defining for conditions #47

@tiholic

Description

@tiholic

Here's an example representation of my models:

class Tag(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

class Activity(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    tags = models.ManyToManyField(Tag, through='TagBinding')

class TagBinding(models.Model):
    tag = models.ForeignKey(Tag)
    activity = models.ForeignKey(Activity)

example picked from this SO Question

And I wanted to make sure tag.user is same as activity.user. So I added the following trigger on TagBinding class

@pgtrigger.register(
    pgtrigger.Protect(
        name='ensure_same_user',
        operation=pgtrigger.Insert | pgtrigger.Update,
        condition=pgtrigger.Q(new__tag__user_id__df=pgtrigger.F('new__activity__user_id'))
        )
    )

Ad when running ./manage.py pgtrigger install, it throws:

django.core.exceptions.FieldDoesNotExist: TagBinding has no field named 'activity__user_id'

Tried dropping the _id from user_id from both F statement and Q 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 :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions