Issue
I am working on a food recipe database web app in Django 4 and want to store an unknown number of ingredients required for a recipe within a given model. The ingredient is described by a name, a volume, and a measuring unit - eg: Sugar 400 grams, Eggs 2 pieces, etc. I am using PostgreSQL
What is the best practice to store such data within a given model while preserving the ability to query the data or do arithmetic operations on the volumes of the ingredients please?
I have found two options so far, but since I am very new to web development, I do not know if they could work:
- Create a separate model for ingredient and use a many-to-many relationship to connect the models but this would create a new object for every instance that for instance volume is different
- Just use TextField() and then use some crazy Regex to separate the ingredients out
Given that I am new to web development, I have no clue what is the most suitable option.
Thanks
Solution
- Create a separate model for ingredient and use a many-to-many relationship...
Many-to-Many relationships are useful when you want to filter recipes by their ingredients. For example, to list all the recipes which contain Eggs or Sugar.
If you want this feature, then you'll have to use many-to-many field.
... but this would create a new object for every instance that for instance volume is different
Many-to-Many fields support a through
argument which allows you to pass an intermediate model to hold the extra data to avoid this problem. See Extra fields on many-to-many relationships in docs.
- Just use TextField() and then use some crazy Regex to separate the ingredients out
If you don't want to filter by ingredients, using a JSONField
is a better choice than ManyToManyField
or TextField
. This will allow you to store data in a structured format, for example:
ingredients = [
{'name': 'Sugar', 'qty': '400 grams'},
{'name': 'Egg', 'qty': '1'},
...
]
P.S.: If you're going to use JSONField
, also take a look at a library I've created called django-jsonform
which is useful for creating user-friendly JSON editing forms in the admin.
Answered By - xyres
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.