5

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

teraflik
  • 52
  • 13
damon
  • 14,485
  • 14
  • 56
  • 75

1 Answers1

12

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 Holcombe
  • 175,848
  • 15
  • 70
  • 63
  • ooh, this is dumb of me. the foreign key relationship belongs to the item! i apologize. i'm editing to reflect the correct code! – damon Nov 20 '08 at 22:30
  • Lol, that's actually how I read it anyway. My answer will work if the ForeignKey is in Item. – Harley Holcombe Nov 20 '08 at 22:34
  • Actually, when I tried to apply this solution, it didn't work! I get the error "'Publisher' object has no attribute 'item_set'". – damon Nov 24 '08 at 19:45
  • 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 Holcombe Nov 24 '08 at 22:55
  • 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? – espenhogbakk Dec 06 '08 at 20:07
  • 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 Holcombe Dec 07 '08 at 04:28