update other objects when saving an object:

10 views
Skip to first unread message

Tim

unread,
Oct 28, 2011, 1:03:42 PM10/28/11
to django...@googlegroups.com
Hi,
I've modeled a Book that has Chapters, with each Chapter having an ordering 'sequence'. 
So when someone decides the first chapter in the book should become the third, they can just change the sequence number.
That's fine, but when that happens, I want the other chapters to automatically change their sequence to reflect the change.

To accomplish this I thought I could add a custom 'save' method to my Chapter model, but I get the message:
'Manager isn't accessible via ChapterMembership instances'

My code seems straightforward enough:

class ChapterMembership(models.Model):
    chapter = models.ForeignKey(Chapter, blank=True, null=True)
    book = models.ForeignKey(Book, blank=True, null=True)
    sequence = models.PositiveIntegerField()

    def save(self):
        chapters = self.objects.filter(book=self.book) # get all instances for the related book
        sequences = [x.sequence for x in chapters] # a list of all the sequence numbers
        if self.sequence in sequences: #if we have a duplicate sequence take care of it
            for chapter in chapters: 
                if self.sequence == chapter.sequence:
                    chapter.sequence = chapter.sequence + 1
                    chapter.save() # makes this a recursive method
        super(ChapterMembership, self).save()

I suppose I'm missing something basic, but I haven't seen an example like this in my searches.
Can anyone see what I'm doing wrong?
thanks,
--Tim


Brett Epps

unread,
Oct 28, 2011, 2:25:59 PM10/28/11
to django...@googlegroups.com
Hi Tim,

The problem is your use of the self keyword when trying to get at the ChapterMembership manager.  Instead of:

chapters = self.objects.filter…

Try:

chapters = ChapterMembership.objects.filter…

Hope that helps,

Brett

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/Aq-9KyCuDHEJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Tim

unread,
Oct 28, 2011, 3:25:11 PM10/28/11
to django...@googlegroups.com
Hi Brian,
That helps indeed! The code is working now; seems like I need to work on the logic, but now I'm getting somewhere.

thanks,
--Tim

Reply all
Reply to author
Forward
0 new messages