Django Rest Framework M2M Through Model字段无法解析

时间:2016-03-28 20:38:51

标签: python django django-rest-framework

以下是我的模特

# Models
class Category(models.Model):
    parent = models.ForeignKey('Category', null=True, blank=True, related_name="children")
    name = models.CharField(max_length=64)
    alternate_naming = models.ManyToManyField('businesses.Office', through='CategoryOfficeNaming', blank=True)


class CategoryOfficeNaming(models.Model):
    category = models.ForeignKey('Category')
    office = models.ForeignKey('businesses.Office')
    name = models.CharField(max_length=64)

这是我的序列化程序

# Serializers
class CategoryOfficeNamingSerializer(serializers.ModelSerializer):
    class Meta:
        model = CategoryOfficeNaming
        fields = (
            'office',
            'name',
        )


class CategorySerializer(serializers.ModelSerializer):
    # We need special recursive serialization here for Category (parent) -> Category (child) relationship
    children = serializers.ListSerializer(read_only=True, child=RecursiveField())
    alternate_naming = CategoryOfficeNamingSerializer(many=True)

    class Meta:
        model = Category
        fields = (
            'children',
            'name',
            'alternate_naming',
        )

尝试序列化类别时出错:

AttributeError at /api/categories/
'Office' object has no attribute 'category'

似乎Serializer(alternate_naming)指向Office实例而不是使用直通模型(CategoryOfficeNaming) - 为什么会这样?我可能正在做些傻事!

1 个答案:

答案 0 :(得分:0)

A,哈!

事实证明我误解了何时通过表格。我最终得到了这种结构,而不是使用直通表,我得到了适用于这种情况的东西:

型号:

# Models
class Category(models.Model):
    parent = models.ForeignKey('Category', null=True, blank=True, related_name="children")
    name = models.CharField(max_length=64)


class CategoryOfficeNaming(models.Model):
    category = models.ForeignKey('Category', related_name="alternate_namings")
    office = models.ForeignKey('businesses.Office')
    name = models.CharField(max_length=64)

串行器:

# Serializers
class CategoryOfficeNamingSerializer(serializers.ModelSerializer):

    class Meta:
        model = CategoryOfficeNaming
        fields = (
            'office',
            'name',
        )


class CategorySerializer(serializers.ModelSerializer):
    # We need special recursive serialization here for Category (parent) -> Category (child) relationship
    children = serializers.ListSerializer(read_only=True, child=RecursiveField())
    alternate_namings = CategoryOfficeNamingSerializer(many=True)

    class Meta:
        model = Category
        fields = (
            'children',
            'name',
            'alternate_namings',
        )