爲了保持我的項目清潔,我決定(可能錯誤地)我一個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}} –
{{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使用的模型,但無法找到任何東西,會給我正確的反應。
那麼有什麼想法?
或者,我只是走下來一個壞的路徑 - 而應該完全考慮到了不同的設計?
嘗試宣稱通過設置查詢集的模型,代理模型,如圖接受答案的最後一個例子在這裏包裝ingredient_set訪問屬性:https://stackoverflow.com/questions/3891880/django-proxy-model-and-外鍵#答案-6988506 – fips