[英]Django Rest Framework: serialize list of ids
Is there a way to serialize request's payload like {'ids': [1,2,3]}
as a ListField of primary keys (ie check by serializer whether Task objects with such ids exist)? 有没有一种方法可以将请求的有效负载序列化为{'ids': [1,2,3]}
作为主键的ListField(即,由序列化程序检查具有此类ID的Task对象是否存在)?
Or what approach should I use to write an API view for another microservice to confirm that tasks were enqueued? 还是应该使用哪种方法为另一个微服务编写API视图以确认任务已入队?
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'})
PrimaryKeyRelatedField
may be used to serialize a list of primary keys. PrimaryKeyRelatedField
可用于序列化主键列表。 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 只需传递queryset
参数以验证字段输入,然后在create
方法内部就可以访问要更新的Task
对象列表
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()
. 请记住, task_list
不是查询集(是Task
对象的列表),将无法调用诸如task_list.update()
类的东西。 Update action must be performed for each object 必须对每个对象执行更新操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.