相关文章推荐

我在 Entity EntityGroup 之间有一个M2M关系,我想把相应的实体索引保存到 EntityGroup 中,就像一个实体数组保存到数据库中一样。

由于我使用了一个自定义的通过模型,里面有额外的字段 index ,我需要将 index 序列化到对应的 entity 到响应,我应该如何实现呢?

我是django和django-rest-framework的新手,在google上搜索了一下,似乎没有类似的M2M例子。我的想法是,一个序列化器只能序列化唯一一个有 ForeignKey 关系的模型字段,一个视图集可以有一个基于 queryset 的自定义模型,可以合并几个模型的关系。所以我需要实现一个更可扩展的视图集,里面有一个自定义的 queryset

Here is my code:

models.py

class Entity(models.Model):
    uuid = models.CharField()
    name = models.CharField()
class EntityGroup(models.Model):
    name = models.CharField()
    entities = models.ManyToManyField(Entity,
        through='EntityGroupRelationship',
        through_fields=('group', 'entity'),
        related_name='groups'
class EntityGroupRelationship(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
    group = models.ForeignKey(EntityGroup, on_delete=models.CASCADE)
    index = models.PositiveIntegerField()

serializers.py

class EntitySerializer(serializers.ModelSerializer):
    class Meta:
        model = Entity
        fields = '__all__'
class EntityGroupRelationshipSerializer(serializers.ModelSerializer):
    class Meta:
        model = EntityGroupRelationship
        fields = '__all__'
class EntityGroupSerializer(serializers.ModelSerializer):
    entities = EntitySerializer(many=True)
    class Meta:
        model = EntityGroup
        fields = '__all__'

views.py

class EntityGroupViewSet(BaseModelViewSet):
    queryset = EntityGroup.objects.all()
    serializer_class = EntityGroupSerializer
class EntityGroupRelationshipViewSet(BaseModelViewSet):
    queryset = EntityGroupRelationship.objects.all()
    serializer_class = EntityGroupRelationshipSerializer

Current response

"id": 1, "entities": [{ "id": 1, "name": "",

Expected respponse

"id": 1, "entities": [ "index": 1, "info": { "id": 1, "name": "",
python
django
django-rest-framework
Itachi
Itachi
发布于 2019-08-06
1 个回答
Sardorbek Imomaliev
Sardorbek Imomaliev
发布于 2019-08-06
已采纳
0 人赞同

你使用的是不正确的序列化器。使用EntityGroupRelationshipSerializer而不是EntitySerializer。此外,你还需要传递正确的fields

class EntitySerializer(serializers.ModelSerializer):
    class Meta:
        model = Entity
        fields = '__all__'
class EntityGroupRelationshipSerializer(serializers.ModelSerializer):
    entity = EntitySerializer()
    class Meta:
        model = EntityGroupRelationship
        fields = ('index', 'entity')
class EntityGroupSerializer(serializers.ModelSerializer):
    entities = EntityGroupRelationshipSerializer(many=True) # here should be EntityGroupRelationshipSerializer
 
推荐文章