views:

1804

answers:

1

Here's my code:

class Publisher(models.Model):
    name = models.CharField(
            max_length = 200,
            unique = True,
    )

    url = models.URLField()

    def __unicode__(self):
        return self.name

    def save(self):
        pass

class Item(models.Model):
    publisher = models.ForeignKey(Publisher)

    name = models.CharField(
            max_length = 200,
    )

    code = models.CharField(
            max_length = 10,
    )

    def __unicode__(self):
        return self.name

I want to be able to access each Item from the Publisher save function. How can I do this?

For instance, I'd like to append text to the "code" field of each Item associated with this Publisher on the save of Publisher.

edit: When I try to implement the first solution, I get the error "'Publisher' object has no attribute 'item_set'". Apparently I can't access it that way. Any other clues?

edit 2: I discovered that the problem occurring is that when I create a new Publisher object, I add Items inline. Therefor, when trying to save a Publisher and access the Items, they don't exist.

Is there any way around this?!

+4  A: 

You should be able to do something like the following:

def save(self, **kwargs):
    super(Publisher, self).save(**kwargs)

    for item in self.item_set.all():
        item.code = "%s - whatever" % item.code

I don't really like what you're doing here, this isn't a good way to relate Item to Publisher. What is it you're after in the end?

Harley
ooh, this is dumb of me. the foreign key relationship belongs to the item! i apologize. i'm editing to reflect the correct code!
Lol, that's actually how I read it anyway. My answer will work if the ForeignKey is in Item.
Harley
Actually, when I tried to apply this solution, it didn't work! I get the error "'Publisher' object has no attribute 'item_set'".
Yeah looking at this again you're going to run into problems. When you first create the publisher, it hasn't got any items, nor does it actually exist yet so you'll have to save it beforehand. I've updated my answer.
Harley
Does this work? Ive tried something simular and i cant get hold of the related objects at first save, only when i save and resave it, the second time I get hold of the objects inside the ForeignKey. Any idea?
Espen Christensen
If you're just creating the Publisher, it won't have any related items. After it's created and has some items it should work properly.
Harley