如何使用django rest框架序列化带有直通模型的ManyToManyField

时间:2013-10-04 11:37:01

标签: python django django-models django-rest-framework

我有一个Recipe模型,它包含一个IngredientType对象的M2M字段。这个字段,也就是ingredient_list,通过一个Ingredient对象使用臭名昭着的“通过”模型,该对象将额外的数据添加到我的IngredientType中。 这些是我的课程:

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)

也就是说,更改Serializer,它可以正常工作,但不会向我提取Ingredient数据。 我用过这个链接: Include intermediary (through model) in responses in Django Rest Framework 作为参考,但显然它没有解决我的问题 任何帮助,将不胜感激。 TNX, Nitzan

1 个答案:

答案 0 :(得分:6)

Recipe模型上,对于ingredient_list字段,您ManyToManyField指向IngredientType

RecipeSerializer ingredient_list字段中,IngredientTypeSerializer字段未使用IngredientSerializer,而是source

这是错误。 (它解释了错误消息 - {{1}}的实际模型没有序列化程序查找的属性。)

除此之外,您的命名方案非常混乱。 “食谱”很好,但你所谓的“IngredientType”应该只是“成分”,然后你应该找到通过表的不同名称。 (也许是“RecipeIngredientDetails”)

我希望有所帮助。