Tuesday, November 30, 2010

Editing a many to many field in a save method

Hi, I've got the following model and I want it so that each delivery
has a default category of undefined

class Delivery(models.Model):
.....
categories = models.ManyToManyField(Category, blank = True, null =
True)
.....

Then if other categories are selected undefined is automatically
removed from the delivery's categories.
I thought I would be able to do this using the save method below, but
it doesn't work. If categories are none it doesn't add undefined and
if serveral are selected it doesn't remove undefined.

def save(self):
super(Delivery, self).save()
if self.categories.count() == 0:
undefined = Category.objects.get(name='undefined')
self.categories.add(undefined)
if self.categories.count() > 1:
undefined = Category.objects.get(name='undefined')
for category in self.categories.all():
if category == undefined:
self.categories.remove(undefined)
super(Delivery, self).save()

if i select/deselect them using the admin interface they work fine,
just not the changes i try to make in save. I'd appreciate any help, I
don't know if i've misunderstood something or if its something else.

thanks

--
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