IainS
IainS

Reputation: 260

Django multiple foreign keys or one enough?

I'm fairly new to Django having up to this point used to it display data from other sources.

I'm embarking on a new project and have a query about the way Django handles model relations (did some searching couldn't find much for this specific instance) and am wondering the most efficient way of accomplishing it.

I have 3 Models, User(obviously :S), Project and Report. Now a report is part of a project and done by a user but project is also 'owned' by a user. In that other users cannot see either the reports/projects of another user. Do i need two foreign keys for Report or just one (e.g User creates projectA and Report1, since Report1 is linked to Project it is also linked to User) ie:

Class Report(models.Model):
    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)

or

Class Report(models.Model):
    project = models.ForeignKey(Project)

Upvotes: 0

Views: 179

Answers (1)

Andrew Gorcester
Andrew Gorcester

Reputation: 19973

If a report is only associated with a user through the project (this means specifically that it makes no sense to have a report with a different user than its project) then the second one is better. You will always be able to access the user by (report object).project.user, or in search queries as 'project__user'. If you use the first one you risk getting the user data for the report and the project out of sync, which would not make sense for your app.

Upvotes: 1

Related Questions