显示模型名称的序列化程序



我想序列化嵌套查询集中的数据:我有工作代码,但串行器的输出显示了太多数据。出于安全考虑,我想把这个藏起来。

示例输出:(…("画廊":"[{"模型":"mainapp.imagesforgallery","pk":1,"字段":{"用户":1、"图像":"上传/2022/8/6/drw/Adapta-KDE-theme_JOgL4kO.webp","缩略图":"}}]";(…(

这是型号.py

class ImagesForGallery(models.Model):
user = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE)
image = models.ImageField(upload_to=user_directory_path, blank=True, null=True)
thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
def __str__(self):
return 'User: {} || Image: {}'.format(self.user, self.image)
class Gallery(models.Model):
project = models.ForeignKey(Projects, null=True, blank=True, on_delete=models.CASCADE)
project_gallery =  models.ManyToManyField(ImagesForGallery, blank=True, related_name='project_gallery')
def __str__(self):
return '{}'.format(self.project)

这是我的观点

class HomeView(viewsets.ModelViewSet):
serializer_class = ProjSerializer
queryset = Proj.objects.all()
def list(self, request, *args, **kwargs):
response = super(HomeView, self).list(request, args, kwargs)
gal = Gallery.objects.all()
for d in response.data:
for g in gal:    
if d['uuid'] == str(g.project.uuid):
qs = g.project_gallery.get_queryset()                
serialized_obj = serializers.serialize('json', qs)    
d['gallery'] = serialized_obj

return response

此代码将项目模型与照片库模型进行比较。如果uuid是正确的,请将此库包含在项目中并发送json。

我不确定代码是否有效和安全。问题是如何修改代码,使其不显示模型名称。

您需要使用ProjSerializer来序列化查询集

if d['uuid'] == str(g.project.uuid):
qs = g.project_gallery.get_queryset()
serialized_obj = ProjSerializer(qs, many=True).data
d['gallery'] = serialized_obj

相关内容

  • 没有找到相关文章

最新更新