我在Entity
和EntityGroup
之间建立了M2M关系,我想将相应的实体索引保存到EntityGroup
,就像将实体数组保存到数据库一样。
由于我在模型中使用了带有附加字段index
的自定义模式,因此我需要将index
序列化为响应的相应entity
,我应该如何实现呢?
我是django和django-rest-framework的新手,在经过几次Google搜索后,似乎没有类似的M2M示例。我的想法是,序列化程序只能序列化具有ForeignKey
关系的唯一模型的字段,视图集可以具有基于queryset
的自定义模型,该模型可以合并几个模型的关系。因此,我需要在内部使用自定义queryset
来实现可扩展的视图集吗?
这是我的代码:
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
当前响应
[
{
"id": 1,
"entities": [{
"id": 1,
"name": "",
}]
},
...
]
预期的响应
[
{
"id": 1,
"entities": [
{
"index": 1,
"info": {
"id": 1,
"name": "",
}
}
]
},
...
]
答案 0 :(得分: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
class Meta:
model = EntityGroup
fields = '__all__'