2017-09-21 55 views
0

問題說明的鏈接的食譜和跟蹤Django模型:批量

假設我有與Django的前端運行多個模型的數據庫。

清單中的一個表格。該清單包括條目具有以下規格:

class InventoryItem(models.Model): 
    item_name = models.TextField(max_length=10) #apple, orange, cilantro, etc... 
    item_quantity = models.DecimalField(...) 

下一個模式將描述什麼是與這些成分

class Product(models.Model): 
    product_name = models.TextField(...) 
    product_description = models.TextField(...) 

ProductItem模型還需要跟蹤取自成分製成通過指定InventoryItem以及從使用的庫存項目中使用的數量來確定庫存。

以前的經驗

在以往的經驗,我已經做了在C#中使用的EntityFramework類似的東西與MySQL。我實現這一目標的方式是使用名爲RecipeElement的另一個表格/模型,其中每個表格都將外鍵輸入到ProductItem條目。該RecipeElement模型看起來像下面這樣:

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) 

的問題

我與Django的這種做法的問題是雙重的:

  1. 我將如何檢索與ProductItem相關的RecipeElement項條目
  2. 用戶如何輸入RecipeElement條目和ProductItem條目在一個頁面上。 (中RecipeElement S表示每個ProductItem的數量沒有限制,但每個RecipeElement僅與一個ProductItem

我使用的SQLite的時刻,但我們計劃轉移到MySQL在未來,如果改變任何關聯。

+0

? –

+0

或多或少。理想情況下,用戶可以在一個視圖中添加一個新的ProductItem並指定其所有的RecipeElement @MauricioCortazar – robotHamster

+1

您可以獲得該對象並使用.add(yourproductitemhere)這就是您的意思? –

回答

1

如果你想檢索所有RecipeElementProduct這樣做:

ProductItem.objects.get(pk=1).recipeelement_set.all() 

在第二個問題,您可以添加一個recipeElement使用.add()create()product:在您要添加一個新的`recipeElement`用`ProductItem`第二個問題

ProductItem.objects.get(pk=1).recipeelement_set.add(your_recipe_element)