2017-05-31 17 views
0

爲了保持我的項目清潔,我決定(可能錯誤地)我一個Django應用程序分成兩個。一個用於管理信息的應用程序,另一個用於顯示。爲此,我認爲在顯示應用中使用Django代理模型將是最好的方法。但是,我在某些模型中遇到了ForeignKey字段的問題,並強制這些外鍵使用代理模型,而不是原始模型。Django的:分裂一個應用程序分成多個:模板,代理模式和ForeignKeys

下面是一些例子來更清楚:

App_1-model.py

class Recipe(models.Model): 
    name = models.CharField(max_length=200) 
    slug = models.SlugField() 
    ... 

class Ingredient(models.Model): 
    name = models.CharField(max_length=200) 
    recipe = models.ForeignKey(Recipe) 
    weight = models.IntegerField() 

App_2-model.py(進口APP_1型號)

class RecipeDisplayProxy(Recipe): 

    class Meta: 
     proxy = True 

    @property 
    def total_weight(self): 
     # routine to calculate total weight 
     return '100g' 


class IngredientDisplayProxy(Ingredient): 

    class Meta: 
     proxy = True 

    @property 
    def weight_lbs(self): 
     # routine to convert the original weight (grams) to lbs 
     return '2lb' 

App_2.views.py

def display_recipe(request, slug): 
    recipe = get_object_or_404(RecipeDisplayProxy, slug=slug) 

    return render(
     request, 
     'display_recipe/recipe.html', 
     {'recipe': recipe} 
     ) 

APP_2-template.html

<h2 class="display-4">{{ recipe.name }}</h2> 
<p>{{ recipe.total_weight }}</p> <!-- This works fine, as expected //--> 

<ul> 
{% for recipe_ingredient in recipe.ingredient_set.all %} 
<li>{{recipe_ingredient.ingredient}} &ndash; 

{{recipe_ingredient.weight_lbs}}</li> 

<!-- 
The above line doesn't return anything as the 'Ingredient' model, not the "IngredientDisplayProxy' is being returned. (As expected) 
--> 

{% endfor %} 
</ul> 

這裏發生的事情是,我成功地返回RecipeDisplayProxy模型視圖中指定,但是當我訪問ingredient_set返回Ingredient模型,而不是IngredientDisplayProxy(如預期)。

那麼,如何強制ingredient_set返回IngredientDisplayProxy車型呢?

我試圖實現在這裏找到代碼: Django proxy model and ForeignKey

但沒有運氣。然後我就開始挖成RecipeDisplayProxy的INIT()方法 - 看看我是否能覆蓋在ingredient_set使用的模型,但無法找到任何東西,會給我正確的反應。

那麼有什麼想法?

或者,我只是走下來一個壞的路徑 - 而應該完全考慮到了不同的設計?

+0

嘗試宣稱通過設置查詢集的模型,代理模型,如圖接受答案的最後一個例子在這裏包裝ingredient_set訪問屬性:https://stackoverflow.com/questions/3891880/django-proxy-model-and-外鍵#答案-6988506 – fips

回答

0

從你正在返回的配方實例的視圖,但在模板您通過訪問配方成分,但它應該是倒過來,從成分可以訪問recipe.Now爲代理模式,更好地閱讀這documentation

0

看起來像我在做事情有些不對,等等fips建議我回去做了以下內容:

class RecipeDisplayProxy(Recipe): 

    class Meta: 
     proxy = True 

    @property 
    def total_weight(self): 
     # routine to calculate total weight 
     return '100g' 

    @property 
    def ingredient_set(self): 
     qs = super(RecipeDisplayProxy, self).ingredient_set 
     qs.model = IngredientDisplayProxy 
     return qs 

很簡單:'(所以謝謝你幫助和建議。

相關問題