I am using Django REST generic views for my API endpoint. One of the field in my serializer has ManyToMany relationship. I want to show that field into my API endpoint, But
You do not need the get_queryset
method you could do something like this:
#views.py
class AlertCreateView(ListCreateAPIView):
queryset = Alert.objects.all()
serializer_class = AlertSerializer
permission_classes = (IsAuthenticated,)
Name the queues
field in the serializer in the same way as it is written in therelated_name
of the model. And your QueueSerializer
can inherit fromPrimaryKeyRelatedField
to be rendered.
#models.py
class AlertModel(models.Model):
...
queues = models.ManyToManyField(Queue, ... related_name='queues')
...
#serializer.py
class QueueSerializer(PrimaryKeyRelatedField, serializers.ModelSerializer):
class Meta:
model: Queue
class AlertSerializer(serializers.ModelSerializer):
queues = QueueSerializer(many=True, queryset=Queue.objects.all())
class Meta:
model = Alert
fields = (
'id', 'name', 'queues','email', 'expected_qos'
)
What can I do ?
Not much since HTML form don't support nested serializers at the moment.
You could use a non nested relational field in the serializer to work this around or just use regular JSON.