在序列化器上找不到字段

时间:2017-02-27 17:22:50

标签: django django-rest-framework

我正在使用DRF构建REST API,目前我一直在为端点/api/v1/venues/1/packages/建模。对此的GET请求给出了这个错误:

  

/ api / v1 / venues / 1 / packages /

中的AttributeError      

尝试在序列化程序item_type上获取字段MenuItemSerializer的值时出现AttributeError。

     

序列化程序字段可能名称不正确,与ManyRelatedManager实例上的任何属性或键都不匹配。

     

原始例外文字是:' ManyRelatedManager'对象没有属性' item_type'。

以下是参与模特:

class MenuItemType(models.Model):
    class Meta:
        db_table = 'menu_item_types'

    name = models.TextField()

class MenuItem(models.Model):
    class Meta:
        db_table = 'menu_items'

    name = models.TextField()
    item_type = models.ForeignKey('MenuItemType', on_delete=models.CASCADE)

class PackageItems(models.Model):
    class Meta:
        db_table = 'package_items'

    package = models.ForeignKey('Package', on_delete=models.CASCADE)
    menu_item = models.ForeignKey('MenuItem', on_delete=models.CASCADE)
    quantity = models.DecimalField(max_digits=10, decimal_places=2)
    comments = models.TextField(null=True)

class Package(models.Model):
    class Meta:
        db_table = 'packages'

    name = models.TextField()
    price = models.DecimalField(max_digits=16, decimal_places=2)
    comments = models.TextField(null=True)

    venue = models.ForeignKey('Venue', on_delete=models.CASCADE)
    menu_items = models.ManyToManyField('MenuItem', through='PackageItems')

和序列化器:

class MenuItemTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = MenuItemType
        fields = ['id', 'name']

class MenuItemSerializer(serializers.ModelSerializer):
    item_type = MenuItemTypeSerializer()
    class Meta:
        model = MenuItem
        fields = ['id', 'name', 'item_type']

class PackageItemSerializer(serializers.ModelSerializer):
    menu_items = MenuItemSerializer()
    class Meta:
        model = PackageItems
        fields = ['id', 'menu_items', 'quantity', 'comments']

class PackageSerializer(serializers.ModelSerializer):
    menu_items = MenuItemSerializer()
    class Meta:
        model = Package
        fields = ['id', 'venue_id', 'name', 'price', 'comments', 'menu_items']

让我先承认我是新的Django和DRF,可能会犯一些愚蠢的错误。因此,批评是最受欢迎的!

1 个答案:

答案 0 :(得分:1)

当您从相关经理调用many=True时,需要设置MenuItemSerializer

class PackageSerializer(serializers.ModelSerializer):
    menu_items = MenuItemSerializer(many=True)

    class Meta:
        model = Package
        fields = ['id', 'venue_id', 'name', 'price', 'comments', 'menu_items']