Monday, October 29, 2012

How to implement clean() for a model with ManyToMany fields?

Hi all,

using Django 1.3.1, I use a model like this:


class KalenderEintrag(models.Model):
id = models.AutoField(primary_key=True)
von = models.DateField(verbose_name=u"\u200Bvon")
bis = models.DateField(verbose_name=u"\u200Bbis")
text = models.CharField(max_length=80)
farbe = models.CharField(max_length=20, blank=True)
regionen = models.ManyToManyField(Region, null=True, blank=True)
kstellen = models.ManyToManyField(Kostenstelle, null=True, blank=True)
bereiche = models.ManyToManyField(Bereich, null=True, blank=True)

def clean(self):
if not self.regionen and not self.kstellen and not self.bereiche:
raise ValidationError("This calender entry won't be
displayed anywhere.")


What I would like to do in clean() is making sure that not all three
ManyToMany fields are empty/blank all at the same time.

However, it doesn't work as shown above:

With pre-existing KalenderEintrag entries whose regionen, kstellen and
bereiche are all empty, the "if not self.regionen and not ..." does not
trigger.

When I try to newly create a KalenderEintrag in the admin, the "if not
self.regionen and not ..." line raises a ValueError exception:
"'KalenderEintrag' instance needs to have a primary key value before a
many-to-many relationship can be used."

How can I properly implement clean() to check the three ManyToMany
fields for non-empty contents?

Best regards,
Carsten



--
Cafu - the open-source Game and Graphics Engine
for multiplayer, cross-platform, real-time 3D Action
Learn more at http://www.cafu.de

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment