2012-05-17 32 views
7

在Django和Tastypie我試圖找出如何妥善處理多對多「通過」的關係,就像那些在這裏找到:https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationshipsDjango的tastypie和多對多「通過」關係

這裏有我的樣本模型:

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應該指向成分而不是配方成分。我會看看這是否能完成這項工作。

編輯:

新錯誤..任何想法? 對象''有一個空的屬性「標題」,不允許默認值或空值。

回答

3

你提到:

I may have found the error myself. ToManyField should be directed toward Ingredient and not RecipeIngredient. I'll see if this does the job.

有一個更好的辦法,雖然[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

在簡短的總結,而不是ToManyField配料,我使用ToManyField朝向ThroughModel。然後將attribute kwargs自定義爲返回ThroughModel Queryset的回調函數。

更新(2014年4月)

這個答案很久以前就有了。不知道它是否仍然有用。

+1

請在這裏列出答案的重要部分。堆棧溢出不是在這裏成爲一個東西的鏈接庫,而是成爲一個答案庫。這也是推廣博客的一種非常不恰當的方式。 –

+0

Duh,好的,我將把答案複製到這裏......因爲帖子太長了...... – Yeo

+2

鏈接似乎現在已經死了 – msc

-2

我和你有同樣的問題。爲了解決這個問題,我只是從API中刪除了ToMany字段(就像在RecipeResource中一樣)。這對我們很有用,因爲模型仍然有manytomany字段(不是API),並且您仍然可以通過查詢中間模型來查詢關係。

+0

這並沒有真正回答這個問題。 – fluffels