Accessing related objects on model.clean()

127 views
Skip to first unread message

Marc Aymerich

unread,
Oct 16, 2013, 9:52:28 PM10/16/13
to django-users
Yep,
I'm writing some validation logic for a model that is being used in an
admin inline form

The model looks like this

class Child(models.Model):
parent = models.ForeignKey(Parent)

def clean(self):
super(....).clean()
if self.parent.surname != self.surname:
raise ValidationError....

The problem is that on the "Parent add admin view" I get a
Parent.DoesNotExist error when I'm saving new Parent and Childs. That
is because when child.clean() is called child.parent_id is None, so
self.parent fails, it looks like self.parent is created afterwards and
is not available at that time.

How can I validate a new child object based on its parent information?
I'm surprised not finding any information regarding this issue :)



Thanks!

--
Marc

Marc Aymerich

unread,
Oct 17, 2013, 6:12:15 PM10/17/13
to django-users
On Wed, Oct 16, 2013 at 11:52 PM, Marc Aymerich <glic...@gmail.com> wrote:
> Yep,
> I'm writing some validation logic for a model that is being used in an
> admin inline form
>
> The model looks like this
>
> class Child(models.Model):
> parent = models.ForeignKey(Parent)
>
> def clean(self):
> super(....).clean()
> if self.parent.surname != self.surname:
> raise ValidationError....
>
> The problem is that on the "Parent add admin view" I get a
> Parent.DoesNotExist error when I'm saving new Parent and Childs. That
> is because when child.clean() is called child.parent_id is None, so
> self.parent fails, it looks like self.parent is created afterwards and
> is not available at that time.

yep this was something related with my application ! it is indeed
possible to access related objects on model clean, sorry for the
noise!

--
Marc
Reply all
Reply to author
Forward
0 new messages