Reputation: 15138
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?!
Upvotes: 5
Views: 7052
Reputation: 182146
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?
Upvotes: 12