Reputation: 649
Problem Description
Suppose I have a database with multiple models running with a Django front-end.
One of the tables in the Inventory. The inventory consists of entries with the following specifications:
class InventoryItem(models.Model):
item_name = models.TextField(max_length=10) #apple, orange, cilantro, etc...
item_quantity = models.DecimalField(...)
The next model will be to describe what is made with those ingredients
class Product(models.Model):
product_name = models.TextField(...)
product_description = models.TextField(...)
The ProductItem
model also needs to keep track of the ingredients taken from inventory by specifying the InventoryItem
and the quantity used from that inventory item used.
Previous Experience
In a previous experience, I have done something similar with EntityFramework in C# with MySQL. The way I achieved that was using another table/model called RecipeElement
, where each one of those would be foreign-keyed to a ProductItem
entry. The RecipeElement
model looked like the following:
class RecipeElement(models.Model):
inventory_item = models.ForeignKey(InventoryItem, on_delete = models.CASCADE)
quantity_used = models.DecimalField(...)
product_item = models.ForeignKey(ProductItem, on_delete = models.CASCADE)
The Issue
My issue with that approach in Django is twofold:
RecipeElement
entries associated with a ProductItem
entryRecipeElement
entries and the ProductItem
entries on one page. (The number of RecipeElement
s for each ProductItem
is not limited, but each RecipeElement
is associated with only one ProductItem
I am using SQLite for the moment but plan to transfer to MySQL in the future, if that changes anything.
Upvotes: 0
Views: 436
Reputation: 4213
If you want to retrieve all the RecipeElement
for a Product
do something like:
ProductItem.objects.get(pk=1).recipeelement_set.all()
In the second issue you can add a recipeElement
from a product
using .add()
or create()
like:
ProductItem.objects.get(pk=1).recipeelement_set.add(your_recipe_element)
Upvotes: 1