我正在研究BlogSerializer
的更新部分。当我调用blog_serializer.data
返回旧数据而不是新数据时,传递给序列化程序的实例将在数据库中更新,但是当我刷新浏览器时,将显示最新数据。我检查了它们在更新时是否不是错误。 所以我如何才能将最新的更新数据显示在可浏览的API中
Serializer.py
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = '__all__'
class BlogFilesSerializer(ModelSerializer):
created_at = serializers.SerializerMethodField()
updated_at = serializers.SerializerMethodField()
class Meta:
model = BlogFilesModel
fields = ('blog_files_id', 'blog', 'path',
'created_at', 'updated_at')
extra_kwargs = {
'path': {
'error_messages': {
'blank': 'File is required'
},
},
'blog' : {
'error_messages': {
'blank': 'blog must be selected'
},
}
}
def get_created_at(self, obj):
formatted_date = obj.created_at.strftime("%d-%m-%Y")
return formatted_date
def get_updated_at(self, obj):
formatted_date = obj.created_at.strftime("%d-%m-%Y")
return formatted_date
class BlogSerializer(ModelSerializer):
blog_files = serializers.SerializerMethodField()
uploaded_files = serializers.FileField(write_only=True, required=True)
blog_created_at = serializers.SerializerMethodField(read_only=False)
class Meta:
model = BlogModel
fields = ('blog_id', 'user', 'title', 'content',
'status', 'blog_files', 'blog_created_at',
'uploaded_files',
)
extra_kwargs = {
'title': {
'error_messages': {
'blank': 'Title field must not be left blank..'
},
'label': 'Enter Blog Title',
'help_text': 'This is help text of title field'
}
}
def __init__(self, *args, **kwargs):
set_read_only_fields = kwargs.pop('set_read_only_fields', None)
if set_read_only_fields:
for field_name in set_read_only_fields:
if self.fields.get(field_name):
if hasattr(self.fields[field_name], 'allow_empty_file'):
self.fields[field_name].allow_empty_file = True
self.fields[field_name].required = False
set_remove_fields = kwargs.pop('set_remove_fields', None)
super(BlogSerializer, self).__init__(*args, **kwargs)
if set_remove_fields:
for field_name in set_remove_fields:
self.fields.pop(field_name)
def create(self, validated_data):
files = validated_data.pop('uploaded_files')
instance = BlogModel.objects.create(**validated_data)
file_list = self.context.get(
'view').request.FILES.getlist('uploaded_files')
info = []
for i in file_list:
row = {
'blog': instance.blog_id,
'path': i
}
info.append(row)
if len(info) > 0:
file_instance = BlogFilesSerializer(data=info, many=True)
if file_instance.is_valid():
file_instance.save()
return instance
def update(self, instance, validated_data):
file_list = validated_data.pop('uploaded_files', None)
instance.title = validated_data.get('title', instance.title)
instance.content = validated_data.get('content', instance.content)
instance.user = validated_data.get('user', instance.user)
instance.status = validated_data.get('status', instance.status)
instance.save()
if not isinstance(file_list, (list)):
file_list = [file_list]
info = []
for i in file_list:
row = {
'blog': instance.blog_id,
'path': i
}
info.append(row)
if len(info) > 0:
file_instance = BlogFilesSerializer(data=info, many=True)
if file_instance.is_valid():
file_instance.save()
return instance
def get_blog_files(self, obj):
info = BlogFilesSerializer(BlogFilesModel.objects.filter(
blog=obj).order_by('-pk'), many=True)
if info.data:
for i in info.data:
user_detail = User.objects.get(pk=obj.user.id)
i.__setitem__('user_detail', UserSerializer(user_detail).data)
if i.get('user_detail'):
try:
del i['user_detail']['password']
except expression as identifier:
pass
return info.data
def get_blog_created_at(self, obj):
formatted_date = obj.created_at.strftime("%d-%m-%Y")
return formatted_date
views.py
class BlogViewSet(viewsets.ModelViewSet):
queryset = BlogModel.objects.all()
lookup_field = 'blog_id'
serializer_class = BlogSerializer
parser_classes = (MultiPartParser, FormParser, FileUploadParser)
def update(self, request, *args, **kwargs):
info = {'msg':'something went wrong'};
partial = kwargs.pop('partial', False)
instance = BlogModel.objects.get(pk=kwargs['blog_id'])
blog_serializer = BlogSerializer(instance,data=request.data,set_read_only_fields=['uploaded_files'],partial=True)
is_valid = blog_serializer.is_valid()
if is_valid:
blog_serializer.save()
return Response(blog_serializer.data) #here i'm getting previous old data insisted on latest one
else:
return Response(blog_serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
编辑1)在serializer.py部分中添加了更多内容
希望我已经为我的问题提供了足够的细节
答案 0 :(得分:0)
如何将return Response(blog_serializer.data)
更改为return Response(blog_serializer.validated_data)
?