7

Django と Tastypie では、https://docs.djangoproject.com/en/dev/topics/db/models/# にあるような、多対多の「スルー」関係を適切に処理する方法を見つけようとしています。多対多関係の余分なフィールド

ここに私のサンプルモデルがあります:

class Ingredient(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

class RecipeIngredients(models.Model):
    recipe = models.ForeignKey('Recipe')
    ingredient = models.ForeignKey('Ingredient')
    weight = models.IntegerField(null = True, blank = True)

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    ingredients = models.ManyToManyField(Ingredient, related_name='ingredients', through='RecipeIngredients', null = True, blank = True)

今私のapi.pyファイル:

class IngredientResource(ModelResource):
    ingredients = fields.ToOneField('RecipeResource', 'ingredients', full=True)

    class Meta:
        queryset = Ingredient.objects.all()
        resource_name = "ingredients"


class RecipeIngredientResource(ModelResource):
    ingredient = fields.ToOneField(IngredientResource, 'ingredients', full=True)
    recipe = fields.ToOneField('RecipeResource', 'recipe', full=True)

    class Meta:
        queryset= RecipeIngredients.objects.all()


class RecipeResource(ModelResource):
    ingredients = fields.ToManyField(RecipeIngredientResource, 'ingredients', full=True)

class Meta:
    queryset = Recipe.objects.all()
    resource_name = 'recipe'

この例に基づいてコードを作成しようとしています: http://pastebin.com/L7U5rKn9

残念ながら、このコードでは次のエラーが発生します。

"error_message": "'Ingredient' object has no attribute 'recipe'"

ここで何が起こっているか知っている人はいますか?または、RecipeIngredientResource に材料の名前を含めるにはどうすればよいですか? ありがとう!

編集:

私は自分でエラーを見つけたかもしれません。ToManyField は、RecipeIngredient ではなく、Ingredient に向ける必要があります。これが機能するかどうかを確認します。

編集:

新しいエラー..何かアイデアはありますか? オブジェクト '' には空の属性 'title' があり、デフォルト値または null 値は許可されていません。

4

2 に答える 2

3

あなたが言及した:

私は自分でエラーを見つけたかもしれません。ToManyField は、RecipeIngredient ではなく、Ingredient に向ける必要があります。これが機能するかどうかを確認します。

[Tastypie M2M] ( http://blog.eugene-yeo.in/django-tastypie-manytomany-through.html ) (古いブログはオフラインです: https://github.com/9gix/eugene- yeo.in/blob/master/content/web/django-tastiepie-m2m.rst )

簡単にまとめると、ToManyFieldto Ingredientsの代わりに、 to にToManyField向かってを使用しThroughModelます。そして、attributeクエリセットを返すコールバック関数になるように kwargs をカスタマイズしますThroughModel

更新 (2014 年 4 月)

この答えはずっと前に作られています。まだ有用かどうかはわかりません。

于 2012-12-03T18:21:48.637 に答える
-2

私はあなたと同じ問題を抱えていました。これを解決するために、ToMany フィールド (RecipeResource など) を API から削除しました。モデルにはまだ manytomany フィールド (API ではない) があり、代わりに中間モデルをクエリすることでリレーションをクエリできるため、これはうまくいきました。

于 2012-06-05T20:01:28.363 に答える