oebfare

Multiple Foreign Keys to Same Model for Inlines

When you are working with a model that has more than one foreign key to the same model and you want to inline that model you will run into problems. The reason why is due to the way inlineformset_factory works. By default it can work out what foreign key on the given model is referenced to the parent. Lets look how you might call inlineformset_factory:

BookFormSet = inlineformset_factory(Author, Book)

The above case is simple. In all likelyhood you will only have one foriegn key to Author. Lets look at a more complex scenerio:

class Person(models.Model):
        name = models.CharField(max_length=100)

class Friendship(models.Model):
        from_friend = models.ForeignKey(Person, related_name="friend_set")
        to_friend = models.ForeignKey(Person, related_name="otherside")

The models above show a more complex case of something you might want to inline. The above Friendship model would likely have more fields to make the inline worth something. Now lets look at how you might construct the inline formset for this:

FriendshipInline = inlineformset_factory(Person, Friendship, fk_name="from_friend")

We have explicitly given a fk_name because by default inlineformset_factory would not have known which foriegn key you intend to use to Person.

Side Note

I did have a two day hiatus in my blogging, but I will make up for those, I promise.

Entry Details

Published: Nov 10, 2008 at 11:26 PM

© 2007 - 2008 Brian Rosner