Django REST:如何在嵌套的 ModelSerializer 中放置数据(更新)
Django REST: How to PUT Data in Nested ModelSerializer (Update)
现在我可以 POST 通过 json 向我的 django 应用程序添加新数据,但无法更新或删除数据。我尝试覆盖 serializer.py 中的更新方法,但它仍然不起作用。数据保持原始值。
我的问题是如何一次更新所有数据并删除数据个体,如子任务数据、朋友数据或聊天室数据。
我的一部分serializer.py
class SubtaskDataSerializer(serializers.ModelSerializer):
class Meta:
model = SubtaskData
fields = ("subtask_name","subtask_deadline","subtask_completion",
"subtask_importance","subtask_item")
depth = 3
class TaskDataSerializer(serializers.ModelSerializer):
SubtaskDatas = SubtaskDataSerializer( many = True )
class Meta:
model = TaskData
fields = ("task_name", "task_is_group",
"task_time", "task_score", "task_member_list",
"task_bulletin","SubtaskDatas")
read_only_fields = ('SubtaskDatas',)
depth = 2
class FriendsDataSerializer(serializers.ModelSerializer):
class Meta:
model = FriendsData
fields = ("friend_name","friend_account")
depth = 2
class UserDataSerializer(serializers.ModelSerializer):
TaskDatas = TaskDataSerializer( many = True )
FriendsDatas = FriendsDataSerializer( many = True )
ChatroomDatas = ChatroomDataSerializer( many = True )
photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = UserData
fields = ("pk","account","password","username","gender","score",
"photo","TaskDatas","FriendsDatas","ChatroomDatas")
read_only_fields = ('TaskDatas','FriendsDatas','ChatroomDatas',)
depth = 1
views.py
@api_view(['GET','POST'])
def jobterm_list(request, format=None):
if request.method=="GET":
UserDatas =list(UserData.objects.all())
serializer = UserDataSerializer(UserDatas,many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = UserDataSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE']) #
def jobterm_detial(request,pk, format=None):
try:
User_Data = UserData.objects.get(pk=pk)
except UserData.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = UserDataSerializer(User_Data)
return Response(serializer.data)
elif request.method == "PUT":
serializer = UserDataSerializer(User_Data,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
elif request.method == "DELETE":
User_Data.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
最后,我尝试像这样相应地定义 update() 方法。
def update(self, instance, validated_data):
instance.account = validated_data['account']
instance.password = validated_data['password']
instance.username = validated_data['username']
instance.gender = validated_data['gender']
instance.score = validated_data['score']
instance.photo = validated_data['photo']
Friends_Datas = User_Datas.get('FriendsDatas')
for friend in Friends_Datas:
friendsdatas, _ = FriendsData.objects.update_or_create(
{'friend_name': friend.get('friend_name')},
friend_account = friend.get('friend_account'),
usersData_id = instance)
Task_Datas = User_Datas.get('TaskDatas')
for task in Task_Datas:
taskdatas, _ = TaskData.objects.update_or_create(
{
'task_is_group' : task.get('task_is_group'),
'task_time' : task.get('task_time'),
'task_score' : task.get('task_score'),
'task_member_list' : task.get('task_member_list'),
'task_bulletin' : task.get('task_bulletin'), },
task_name = task.get('task_name'),
userData_id = instance
)
Subtask_Datas = task.get('SubtaskDatas')
for subtask in Subtask_Datas:
subtaskdatas = SubtaskData.objects.update_or_create(
{'subtask_deadline' : subtask.get('subtask_deadline'),
'subtask_completion' : subtask.get('subtask_completion'),
'subtask_importance' : subtask.get('subtask_importance'),
'subtask_item' : subtask.get('subtask_item'), }
,subtask_name = subtask.get('subtask_name'),
taskData_id = taskdatas
)
Chatroom_Datas = User_Datas.get('ChatroomDatas')
for chatroom in Chatroom_Datas:
chatroomdatas, _ = ChatroomData.objects.update_or_create(
{'chatroom_contents' : chatroom.get('chatroom_contents'),},
chatroom_member = chatroom.get('chatroom_member'),
userdata_cid = instance
)
return instance
现在我可以 POST 通过 json 向我的 django 应用程序添加新数据,但无法更新或删除数据。我尝试覆盖 serializer.py 中的更新方法,但它仍然不起作用。数据保持原始值。
我的问题是如何一次更新所有数据并删除数据个体,如子任务数据、朋友数据或聊天室数据。
我的一部分serializer.py
class SubtaskDataSerializer(serializers.ModelSerializer):
class Meta:
model = SubtaskData
fields = ("subtask_name","subtask_deadline","subtask_completion",
"subtask_importance","subtask_item")
depth = 3
class TaskDataSerializer(serializers.ModelSerializer):
SubtaskDatas = SubtaskDataSerializer( many = True )
class Meta:
model = TaskData
fields = ("task_name", "task_is_group",
"task_time", "task_score", "task_member_list",
"task_bulletin","SubtaskDatas")
read_only_fields = ('SubtaskDatas',)
depth = 2
class FriendsDataSerializer(serializers.ModelSerializer):
class Meta:
model = FriendsData
fields = ("friend_name","friend_account")
depth = 2
class UserDataSerializer(serializers.ModelSerializer):
TaskDatas = TaskDataSerializer( many = True )
FriendsDatas = FriendsDataSerializer( many = True )
ChatroomDatas = ChatroomDataSerializer( many = True )
photo = Base64ImageField(
max_length=None, use_url=True,
)
class Meta:
model = UserData
fields = ("pk","account","password","username","gender","score",
"photo","TaskDatas","FriendsDatas","ChatroomDatas")
read_only_fields = ('TaskDatas','FriendsDatas','ChatroomDatas',)
depth = 1
views.py
@api_view(['GET','POST'])
def jobterm_list(request, format=None):
if request.method=="GET":
UserDatas =list(UserData.objects.all())
serializer = UserDataSerializer(UserDatas,many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = UserDataSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE']) #
def jobterm_detial(request,pk, format=None):
try:
User_Data = UserData.objects.get(pk=pk)
except UserData.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = UserDataSerializer(User_Data)
return Response(serializer.data)
elif request.method == "PUT":
serializer = UserDataSerializer(User_Data,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
elif request.method == "DELETE":
User_Data.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
最后,我尝试像这样相应地定义 update() 方法。
def update(self, instance, validated_data):
instance.account = validated_data['account']
instance.password = validated_data['password']
instance.username = validated_data['username']
instance.gender = validated_data['gender']
instance.score = validated_data['score']
instance.photo = validated_data['photo']
Friends_Datas = User_Datas.get('FriendsDatas')
for friend in Friends_Datas:
friendsdatas, _ = FriendsData.objects.update_or_create(
{'friend_name': friend.get('friend_name')},
friend_account = friend.get('friend_account'),
usersData_id = instance)
Task_Datas = User_Datas.get('TaskDatas')
for task in Task_Datas:
taskdatas, _ = TaskData.objects.update_or_create(
{
'task_is_group' : task.get('task_is_group'),
'task_time' : task.get('task_time'),
'task_score' : task.get('task_score'),
'task_member_list' : task.get('task_member_list'),
'task_bulletin' : task.get('task_bulletin'), },
task_name = task.get('task_name'),
userData_id = instance
)
Subtask_Datas = task.get('SubtaskDatas')
for subtask in Subtask_Datas:
subtaskdatas = SubtaskData.objects.update_or_create(
{'subtask_deadline' : subtask.get('subtask_deadline'),
'subtask_completion' : subtask.get('subtask_completion'),
'subtask_importance' : subtask.get('subtask_importance'),
'subtask_item' : subtask.get('subtask_item'), }
,subtask_name = subtask.get('subtask_name'),
taskData_id = taskdatas
)
Chatroom_Datas = User_Datas.get('ChatroomDatas')
for chatroom in Chatroom_Datas:
chatroomdatas, _ = ChatroomData.objects.update_or_create(
{'chatroom_contents' : chatroom.get('chatroom_contents'),},
chatroom_member = chatroom.get('chatroom_member'),
userdata_cid = instance
)
return instance