Mutually exclusive fields in model validation

1,084 views
Skip to first unread message

Sonal Breed

unread,
Sep 15, 2009, 5:33:36 PM9/15/09
to Django users
Hi all,

I have a model wherein I want to put a validation as
You must enter Field1 or Field2, but not both.

This model is at the back end and not visible through forms.
How do I accomplish it?

Thanks,

Sincerely,
Sonal

J. Cliff Dyer

unread,
Sep 15, 2009, 6:08:31 PM9/15/09
to django...@googlegroups.com
Override the save method on your model, something like:

class MyModel(models.Model):
field1 = models.TextField(blank=True)
field2 = models.TextField(blank=True)

def save(self):
if (self.field1 and self.field2):
raise ModelValidationError, "only one can live"
elif (not self.field1 and not self.field2):
raise ModelValidationError, "one must live"
else:
super(MyModel, self).save()

Untested code. I don't remember if ModelValidationError exists, and I
don't know if you need to tweak the signature on your save method, but
that should get you pointed in the right direction.

Cheers,
Cliff

Sonal Breed

unread,
Sep 15, 2009, 6:19:26 PM9/15/09
to Django users
Thanks a lot Cliff, I implemented it in a similar manner, just wanted
to know if we
have anything like validation rules a la Access.

Thanks again,
Sincerely,
Sonal.

Daniel Roseman

unread,
Sep 16, 2009, 2:50:17 AM9/16/09
to Django users
On Sep 15, 11:19 pm, Sonal Breed <sonal.br...@gmail.com> wrote:
> Thanks a lot Cliff, I implemented it in a similar manner, just wanted
> to know if we
> have anything like validation rules a la Access.
>
> Thanks again,
> Sincerely,
> Sonal.

Not yet. Honza Kral's Google Summer of Code project for model
validation is due to be merged reasonably soon though, so this will be
in version 1.2 - or in trunk at some earlier point if you don't want
to wait that long.
--
DR.
Reply all
Reply to author
Forward
0 new messages