Django Rest框架 - M2M通过

时间:2016-10-10 18:43:04

标签: json django django-rest-framework relationship m2m

我无法从序列化程序中检索所需的所有字段。 情形:

我有两张桌子:Item&仓库。这些表通过名为InventoryStatus的表通过M2M关系连接。我需要的是从InventoryStatus表中获取带有嵌套仓库信息+状态字段的项目信息。 问题是,我无法获得"状态"场....

型号:

class InventoryItem(models.Model):
    id  = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=25, null=False, blank=True)
    orgid = models.ForeignKey('glonass.Company', null=True, related_name='inventory_items_company')
    title = models.CharField(max_length=150, null=False, blank=True)
    inventory = models.ManyToManyField('CompanyBranch', through='InventoryStatus', related_name='branch_iventoryStatus')

class CompanyBranch(BaseDataDescTime, LocationInfo, PostInfo, PoboxInfo, ContactInfo):
    id  = models.UUIDField(primary_key=True, default=uuid.uuid4,
    orgid = models.ForeignKey('glonass.Company', null=True, related_name='branches')
    slug = models.SlugField(max_length=150, blank=True, null=False)

class InventoryStatus(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    inventoryitem = models.ForeignKey('InventoryItem', related_name='inventory_status_items', null=True)
    orgid = models.ForeignKey('Company', null=True, related_name='inventory_status_company')
    companybranch = models.ForeignKey('CompanyBranch', related_name='inventory_status_warehouses', null=True)
    status = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True, default=0)

串行器:

class InventoryStatusSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = InventoryStatus

class CompanyBranchSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CompanyBranch

class InventoryItemSerializer(serializers.HyperlinkedModelSerializer):
    inventory = CompanyBranchSerializer(many=True)

    class Meta:
        model = InventoryItem

需要输出:

[
    {
        'id': 'xxxxxxxxxxxxx',
        'title': 'Car',
        'inventory': [
            {
                'id': 'yyyyyyyyyyy',
                'title': 'warehouse 1',
                'status': 50
            },
            {
                'id': 'zzzzzzzzzzzz',
                'title': 'warehouse 2',
                'status': 10
            }
        ]
    }
]

2 个答案:

答案 0 :(得分:2)

问题是M2M关系直接给出相关对象而没有“直通”表上的任何信息,当你想在“通过”表中序列化并获取一些信息时会很麻烦。为了解决这个问题,我通常使用“通过”关系从“通过”表和相关项中获取信息。

在你的情况下,它可能看起来像:

class InventoryStatusSerializer(serializers.ModelSerializer):
    companybranch = CompanyBranchSerializer(many=True, read_only=True)
    class Meta:
        model = InventoryStatus
        fields = ('status', 'companybranch')

class InventoryItemSerializer(serializers.ModelSerializer):
    inventory = InventoryStatusSerializer(source='inventory_status_items', many=True, read_only=True)

    class Meta:
        model = InventoryItem

这会产生类似的输出(注意:我认为你的意思是'slug',而不是你的例子的库存项目中的'title'):

[
  {
    'id': 'xxxxxxxxxxxxx',
    'title': 'Car',
    'inventory': [
        {
            'status': 50
            'companybranch': {
                'slug': 'warehouse 1',
                'id': 'yyyyyyyyyyy',                }
        },
        {
            'status': 10
            'companybranch':  {
                'slug': 'warehouse 2',
                'id': 'zzzzzzzzzzzz',
            }
        }
    ]
  }
]

现在,如果您想展平输出,只需更改InventoryStatusSerializer

即可
class InventoryStatusSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='companybranch.id')
    slug = serializers.ReadOnlyField(source='companybranch.slug')
    class Meta:
        model = InventoryStatus
        fields = ('status', 'id', 'slug')

答案 1 :(得分:0)

您需要将字段部分添加到序列化程序'类如下:

   class CompanyBranchSerializer(serializers.HyperlinkedModelSerializer):
      class Meta:
         model = CompanyBranch
         fields = = ('id', 'orgid', 'slug')

你也需要为其他人做同样的事情。