Django Rest Framework: serialize list of ids

Viewed 2678

Is there a way to serialize request's payload like {'ids': [1,2,3]} as a ListField of primary keys (i.e. check by serializer whether Task objects with such ids exist)?

Or what approach should I use to write an API view for another microservice to confirm that tasks were enqueued?

serializer = ConfirmationSerializer(
    data=request.data, many=True
)
queryset = Task.objects.filter(
    ids_in=serializer.data.ids,
    status=Task.STATUS_CREATED,
)

queryset.update(
    status=Task.STATUS_SENT,
    confirmed_at=dt.datetime.now()
)
return Response({'status': 'ok'})
1 Answers

PrimaryKeyRelatedField may be used to serialize a list of primary keys. Just pass the queryset argument to validate the field input and inside create method you will have access to a list of Task objects to update

class ConfirmationSerializer(Serializer):
    tasks_ids = PrimaryKeyRelatedField(
        many=True, 
        queryset=Task.objects.filter(status=Task.STATUS_CREATED)
    )

    def create(self, validated_data):
        task_list = validated_data['tasks_ids']

        # Update the tasks here
        update_task_list(task_list)

Remember that task_list is not a queryset (is a list of Task objects), it will not be possible call something like task_list.update(). Update action must be performed for each object

Related