0

How can one ensure that a foreignkey (Value.user) from one object (Value) corresponds to the foreignkey (Value.userobject) of another foreignkey object (UserObject.user):

Value.userobject.user == Value.user

class UserObject(Model):
    user = ForeignKey(User, on_delete=CASCADE) 
    dummyvalue = DecimalField(max_digits=18, decimal_places=10)


class Value(Model):
    user = ForeignKey(User, on_delete=CASCADE)
    # Ensure the object is owned by user, ie. userobject.user == user..
    userobject = ForeignKey(UserObject, related_name='TheUsersObject', on_delete=CASCADE)
    dummyvalue = DecimalField(max_digits=18, decimal_places=10)

    class Meta:
        constraints = [
            CheckConstraint(
                name="%(app_label)s_%(class)s_same_object_owner",
                check=(
                    Q(
                        ...
                    )
        ]

Currently I can think of handling this when processing the request, but would much prefer handling this as a model constraint if possible.

LeOverflow
  • 301
  • 1
  • 2
  • 16
  • 1
    That's not possible, you can only write checks that span *one* table. – Willem Van Onsem Jun 10 '21 at 19:31
  • Thanks Willem! Incredible speed just as the last time :) – LeOverflow Jun 10 '21 at 19:32
  • You can `raise ValidationError(errors)` on `def clean(self)` method. https://stackoverflow.com/a/8771277/842935 – dani herrera Jun 10 '21 at 20:44
  • @daniherrera Hmmm.. Tried following it, yielding the following: ``` def clean(self): if self.user != self.userobject.user: raise ValidationError(_('Operation not owned by user'))``` which didn't work. – LeOverflow Jun 10 '21 at 21:33
  • `clan`is just for form validations. If you are saving model out of a form validation or admin you should to override `asve` method to call the validations. – dani herrera Jun 11 '21 at 06:09

0 Answers0