Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django foreign key access in save() function

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

like image 895
damon Avatar asked Nov 20 '08 22:11

damon


People also ask

How use Django save method?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

How does Django store ForeignKey values?

Note that the _id in the artist parameter, Django stores foreign keys id in a field formed by field_name plus _id so you can pass the foreign key id directly to that field without having to go to the database again to get the artist object.

Does Django automatically index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

How does ForeignKey work in Django?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.


1 Answers

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?

like image 61
Harley Holcombe Avatar answered Sep 27 '22 23:09

Harley Holcombe