简体   繁体   English

将相关图像发送到 Django Rest 框架

[英]Send related image to Django Rest Framework

Hello everyone reading this post.大家好,阅读这篇文章的人。 I got such issue.我遇到了这样的问题。 So, first of all I have such models layout所以,首先我有这样的模型布局

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
description = models.TextField(max_length=4000, null=True)
liked_profiles = models.ManyToManyField('self', related_name='likes')
disliked_profiles = models.ManyToManyField('self', related_name='dislikes')

class Image(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='images', max_length=6)
path = models.ImageField(upload_to='profile_images')

So, I want to create a drf endpoint that will receive some kind of image, create it, and link to the profile model.所以,我想创建一个 drf 端点,它将接收某种图像,创建它,并链接到配置文件 model。 But I really not sure how to implement this(I want to make it with django viewsets).但我真的不确定如何实现这一点(我想用 django 视图集来实现)。

The main goal is not to provide another viewset class (like ImageViewSet), but to make it part of ProfileViewSet.主要目标不是提供另一个视图集 class(如 ImageViewSet),而是使其成为 ProfileViewSet 的一部分。 So now I have such viewset (contains a method to update the description)所以现在我有了这样的视图集(包含更新描述的方法)

class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
permission_classes = (IsAuthenticated, )

@action(detail=True, methods=['PUT'])
def set_description(self, request, pk=None):
    profile = self.get_object()
    serializer = DescriptionSerializer(data=request.data)
    if serializer.is_valid():
        profile.description = request.data['description']
        profile.save()
    else:
        return Response(serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)

I want to add something like "add_image" method to it.我想向它添加类似“add_image”方法的东西。

How can I implement it and is it actually possible(otherwise you can help me to implement it with another viewset)?我该如何实现它,它实际上是否可能(否则你可以帮助我用另一个视图集来实现它)? I will be extremely grateful for your help我将非常感谢您的帮助

You can do sth similar to your set_description:你可以做类似于你的 set_description 的事情:

@action(
    detail=True,
    methods=["post"],
    serializer_class=ImageSerializer, # write your custom serializer, override save() method and save images from self.context["request"].FILES.items()
)
def create_image(self, request, pk=None):
    instance = self.get_object()
    serializer = self.get_serializer(instance, data=self.request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM