I have a model (let's call it MyModel) with a ManyToManyField called
categories to another model (let's call it MyCategory). MyCategory has a
boolean field called locked that, when true, indicates that new
relationships from MyModel to MyCategory should be forbidden (but existing
ones should be left alone). Since we're already overriding the save method
on MyModel, I thought I could do something like this in MyModel.save():

try:
    oldself = self.__class__.objects.get(pk=self.id)
except self.__class__.DoesNotExist:
    # do the save; if it hasn't been saved yet it can't have any categories
oldcats = [cat.id for cat in oldself.categories.all()]
for cat in self.categories.all():
    if cat.locked and cat.id not in oldcats:
        # trying to add to a locked category; raise an exception
#do the save, any categories being added are unlocked

To my surprise, this doesn't work; I added some print statements before the
for loop, and I see that self.categories.all() always has the same objects
as oldself.categories.all(). I expected that oldself.categories.all() would
show the category status from the DB's point of view, and not the new status
that is in the process of being saved. This old thread:

http://groups.google.com/group/django-users/browse_thread/thread/440290aee0b4ff60/e885f53348110dc6

suggests the same approach I am trying to use.

So, what did I do wrong? Are ManyToManyFields special somehow? Could this
have to do with the fact that my test code runs inside a method decorated
with @django.db.transaction.commit_on_success?

Alexey

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to