Friday, October 28, 2011

Re: update other objects when saving an object:

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

From: Tim <jtim.arnold@gmail.com>
Reply-To: <django-users@googlegroups.com>
Date: Fri, 28 Oct 2011 10:03:42 -0700
To: <django-users@googlegroups.com>
Subject: 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