1 回答
TA贡献1802条经验 获得超5个赞
您可能需要更改模型以允许 roster 有多个成员,或者为 roster 执行多对多或将 FK 关系放在用户身上。因此,您可以为一个名册添加多个成员。
为此,您可以使用这样的自定义路线。下面显示 add_member 和 remove_member 类似,修改为从 members_set 中删除名册对象。
class RosterViewSet(viewsets.ModelViewSet):
queryset = Roster.objects.all().order_by('-id')
serializer_class = RosterSerializer
@action(detail=True, methods=['post'])
def add_member(self, request, pk=None):
errors = []
response = {}
roster = self.get_object()
members_dict = request.data['members']
if not isinstance(members_dict, list):
errors.append("Invalid request format")
else:
for id in members_dict:
try:
member = User.objects.get(pk=id)
roster.members.add(member)
roster.save()
status_code = status.HTTP_200_OK
except Member.DoesNotExist:
errors.append("Member id {} not found".format(id))
if errors:
response['errors'] = errors
status_code = status.HTTP_400_BAD_REQUEST
return response.Response(response, status=status_code)
添加回答
举报