0

Postgresql has a nice syntax for conditionally inserting:

INSERT INTO child (name, parent_id)
SELECT :name, :parent_id
WHERE EXISTS (
    SELECT 1
    FROM parent
    WHERE id = :parent_id 
        AND parent.user_id = :user_id
)

In the above example, nothing would be inserted into the child unless the given :user_id was the owner of the parent row.

Is it possible to simulate this kind of insert in Django?

Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231

1 Answers1

0

You can used a clean method in model class:

from django.utils.translation import gettext as _
from django.core.exceptions import  ValidationError

def clean(self): 
    if  self.parent_id and self.parent.user_id  != self.user_id: 
        raise ValidationError({'user': _('an user must be same as user of  parent.')})