Я пытаюсь переопределить DRF ModelSerializer
, чтобы я мог передать ему список RemoteServer
pk, и он создаст TaskTarget
экземпляров с полем сервера, равным серверу.
Идеяэто то, что я мог бы отправить это на RemoteTaskSerializer
:
{
// RemoteServer pk's
targets: [1,2,3]
// Rest of fields
name: "Test"
}
И в итоге я получу три TaskTarget
экземпляра в RemoteTask.target
, первый из которых указывает на TaskTarget(server=RemoteServer.objects.get(pk=1))
, и так далее.
Сериализатор, который дает мне проблемы:
class RemoteTaskSerializer(serializers.ModelSerializer):
targets = serializers.ListField(child=serializers.IntegerField())
class Meta:
model = RemoteTask
fields = ("name", "targets", "id")
def create(self, validated_data):
server_ids = validated_data.pop('targets', [])
remote_task = RemoteTask.objects.create(**validated_data)
for pk in server_ids:
t = TaskTarget(server=RemoteServer.objects.get(pk=pk))
t.save()
remote_task.targets.add(t)
return remote_task
Модели:
class RemoteTask(models.Model):
name = models.CharField(max_length=120, unique=True)
targets = models.ManyToManyField(TaskTarget)
class TaskTarget(models.Model):
server = models.ForeignKey("RemoteServer", on_delete=models.CASCADE)
output = models.TextField(null=True)
huey_id = models.IntegerField(unique=True, null=True)
class RemoteServer(models.Model):
name = models.CharField(max_length=120, unique=True)
ip = models.GenericIPAddressField()
port = models.PositiveIntegerField()
А вот полный возвратный след:
Traceback (most recent call last):
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/home/h/PycharmProjects//backendapi/views.py", line 47, in post
return self.create(request, *args, **kwargs)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/mixins.py", line 20, in create
headers = self.get_success_headers(serializer.data)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 559, in data
ret = super().data
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 261, in data
self._data = self.to_representation(self.instance)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 526, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/home/h/PycharmProjects//venv/lib/python3.7/site-packages/rest_framework/fields.py", line 1660, in to_representation
return [self.child.to_representation(item) if item is not None else None for item in data]
TypeError: 'ManyRelatedManager' object is not iterable