I have a recipe model that contains the M2M field of an IngredientType object. This field, for example, componentent_list, uses the infamous "pass-through" model through the Ingredient object, which adds additional data to its IngredientType. these are my classes:
class Recipe(models.Model): user_profile = models.ForeignKey(UserProfile, null=True, blank = True) name = models.CharField(max_length=200) photo1 = models.ImageField( upload_to = 'images/recipies', help_text="This photo will show by default") ingredient_list = models.ManyToManyField(IngredientType,through='Ingredient') class Ingredient(models.Model): ingredient_type = models.ForeignKey(IngredientType) recipe = models.ForeignKey(Recipe) amount = models.IntegerField() units = models.CharField(max_length=4,choices=UNIT, default=None, null=True, blank = True) class IngredientType(models.Model): name = models.CharField(max_length=200) plural_name = models.CharField(max_length=200) photo = models.ImageField( upload_to = 'images/ingredients') is_main = models.BooleanField()
I tried serializing them using rest_framework:
class IngredientTypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = IngredientType fields=('name', 'plural_name', 'photo', 'is_main') class IngredientSerializer(serializers.HyperlinkedModelSerializer): ingredient_type = IngredientTypeSerializer(source = 'ingredient_type') amount = serializers.Field(source='ingredient_type.amount') units = serializers.Field(source='ingredient_type.units') recipe = serializers.Field(source='Recipe.name') class Meta: model = Ingredient fields=('amount', 'units') class RecipeSerializer(serializers.ModelSerializer): ingredient_list = IngredientSerializer(source='ingredient_list', many=True, read_only = True) class Meta: model = Recipe fields = ('user_profile', 'name','photo1','ingredient_list')
but when I try to run this, I get an AttributeError: The object "IngredientType" does not have the attribute "componentent_type"
clear when i change the line:
ingredient_list = IngredientSerializer(source='ingredient_list', many=True, read_only = True)
in
ingredient_list = IngredientTypeSerializer(source='ingredient_list', many=True, read_only = True)
that is, change the Serializer, it works, but without collecting the Ingredient data. I used this link: Include the intermediary (through the model) in the answers in the Django Rest Framework as a link, but obviously it did not solve my problems.
Any help would be greatly appreciated. Ty, nitzan