I have a M2M relationship between the Entity
and EntityGroup
and I want to save the corresponding entity index to the EntityGroup
just like an entity array to database.
Since I used a custom through Model with additional field index
inside, I need to serialize the index
to the corresponding entity
to the response, how should I implement that?
I'm new to django and django-rest-framework and it seems there are not similar M2M examples after a few google search. Here is my thought, a serializer could only serialize the only one model's fields with ForeignKey
relationship, a viewset could have a custom model based on queryset
which could merge the relationships for a few models. So I need to implement a more expandable viewset with a custom queryset
inside?
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": "",
}
}
]
},
...
]