Friday, July 17, 2009

Class definition order between two related classes

I ran into an issue where I wanted to have a foreign key to one class then over ride the save in the other class to update the current class. It would through and error because one of the classes was not defined. I finally found this post Class definition order between two related classes and see that you can but the models name in quotes in the foreign key. example:
class Foo(models.Model):
    bar = models.ForeignKey("Bar")
    name = models.CharField(max_length=100)

class Bar(models.Model):
    name = models.CharField(max_length=100)
    def save(self):
        foos = Foo.objects.filter(item=self)         
        foos.update(name=self.name)
        super(Bar, self).save()

No comments: