views:

41

answers:

1

I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps...

#article.models
from someapp.author.models import Author

class Article(model.Model):
    ...
    author = models.ForeignKey(Author)


# author.models
class Author(model.Model):
    ...

From this schema I want to be able to get all the articles by an author. Something like:
author = Author(pk=1)
articles = author.articles

My first reaction was to write a method that did a simple look up in the article model based on the authors ID. What happened here was a never ending inclusion loop because of the separate files. Article needed Author imported to use for the ForeignKey and Author needed article included to use for the model look up. This felt hacky and wrong. I would much rather do it the right way... So, what is the Django way?

+2  A: 

I think this is what you're asking for...

class Article(model.Model):
    ...
    author = models.ForeignKey(Author, related_name='articles')

On a side note, by default without changing anything you've got, I think this would work for you...

article.author_set

But to maintain the article.authors syntax you mention above, you can specify that yourself with related_name.

T. Stone
Wow. I really over complicated that and misunderstood the documentation. Exactly what I was looking for. Thank you.
CrashRoX
@CrashRoX: You should accept this answer if it helped you.
Felix Kling