我有一个 Recipe 模型,其中包含一个 IngredientType 对象的 M2M 字段。这个字段,又名成分列表,通过一个成分对象使用臭名昭著的“通过”模型,该对象将额外数据添加到我的成分类型。这些是我的课:
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()
我尝试使用 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')
但是当试图运行它时,我得到一个 AttributeError :'IngredientType'对象没有属性'ingredient_type'
显然,当我换行时:
ingredient_list = IngredientSerializer(source='ingredient_list', many=True, read_only = True)
至:
ingredient_list = IngredientTypeSerializer(source='ingredient_list', many=True, read_only = True)
也就是说,更改序列化程序,它可以工作,但没有获取我的成分数据。我使用了这个链接:
在 Django Rest Framework 的响应中包含中介(通过模型)
作为参考,但显然它并没有解决我的问题。
任何帮助,将不胜感激。tnx, 尼赞