In Django and Tastypie, I am trying to figure out how to handle many many cross-cutting relationships, such as those found here: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields- on-many-to-many-relationships
Here are my sample 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)
Now my api.py file:
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'
I am trying to create code in this example: http://pastebin.com/L7U5rKn9
Unfortunately, with this code, I get this error:
"error_message": "'Ingredient' object has no attribute 'recipe'"
Does anyone know what is going on here? Or how can I include an ingredient name in a RecipeIngredientResource? Thanks!
EDIT:
Perhaps I myself found a mistake. ToManyField should be directed to the Ingredient, and not to the RecipeIngredient. I'll see if this can handle this.
EDIT:
New mistake .. any ideas? Object '' has an empty attribute 'title' and does not accept default or null values.