2017-05-31 6 views
0

私のプロジェクトをきれいに保つため、1つのDjangoアプリケーションを2つに分割することにしました。情報の管理のための1つのアプリ、表示用のもう1つのアプリ。そしてこれのために、私はDjango Proxy Modelをディスプレイアプリケーションで使うのが最善の方法だと思っていました。しかし、特定のモデル内のForeignKeyフィールドに問題があり、それらの外部キーに、元のモデルではなくプロキシモデルを使用させるように強制しました。Django:1つのアプリケーションを複数に分割する:テンプレート、プロキシモデル、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} 
     ) 
ここで何が起こっている10 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を(返します)。

代わりに、代わりにIngredientDisplayProxyモデルを返すようにするにはどうしたらよいですか?

私はここで見つけたコードの実装しようとした: Django proxy model and ForeignKey

をしかし、運がなかったです。次に、recipeDisplayProxyののinit()メソッドを調べ始めました。これは、ingredients_setで使用されているモデルを上書きできるかどうかを調べるために、私に正しい応答を与えるものは見つかりませんでした。

だからアイデアはありますか?

または、私はこれを悪い方法で解決していますか?全く異なるデザインを検討する必要がありますか?

+0

クエリーセットのモデルをプロキシモデルに設定することにより、ingredients_setアクセスをラップするプロパティを宣言してください。ここでは、受け入れられた回答の最後の例を参照してください。https://stackoverflow.com/questions/3891880/django-proxy-model-and-外部キー#答え-6988506 – fips

答えて

0

レシピインスタンスを返しているビューから、レシピを使用して原料にアクセスしているテンプレートでは、レシピにアクセスできる成分からもう一方の方向に丸くする必要があります。プロキシモデルの場合は、私はいくつかの物事がうまくやっていたように、より良い、この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 

それは簡単なことだった: '(そうありがとうございました助けと提案。

関連する問題