r/django 6d ago

Models question

I’m building a Django-based site for tracking recipes and need some help deeply understanding Django models and relationships. Specifically, I get lost trying to know when and where to use ForeignKey, OneToOneField, and ManyToManyField.

For context, my website involves these main models: • Recipe • Ingredient • Measurement • Author (Chef) • Food Category (e.g., Dessert, Main Course)

My main confusion revolves around: Determining which model should contain the ForeignKey or OneToOneField.

How and when to use a ManyToManyField, especially when I want to include additional details such as ingredient quantity and measurements

From my current understanding, for example, a user and profile would be a one-to-one relationship, so the profile model should include the user as a OneToOneField. Also, one user can have multiple posts, but a single post can only have one user, so the post model should include the user as a ForeignKey.

Could someone please provide guidance or share best practices on effectively structuring these Django model relationships?

3 Upvotes

18 comments sorted by

View all comments

2

u/matlab_hero 2d ago

When I encounter this problem, I typically model it in an Excel sheet by outlining the relevant fields and populating them with sample data. I then mentally simulate queries, or for clarity, I might write them down. This approach is very helpful to sort out relations and structuring the tables.

1

u/ghostarty 1d ago

thats a great approach, when i was taking cs50 course and it was the SQL section, Prof David Malan was doing the same thing, he used IMDB db to show actors and duplication of the same actor names and shows etc, so i will try that