Friday, October 28, 2011

update other objects when saving an object:

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


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