简体   繁体   English

如何获取当前 object 的 ID

[英]how to get id of current object

how to get current id instead of static id (7) to add image to flat如何获取当前 id 而不是 static id (7) 以将图像添加到平面

''' '''

class CreateFlat(CreateAPIView):
serializer_class = CreateFlat
queryset = Flat.objects.all()
permission_classes = [AllowAny]

def post(self, request, *args, **kwargs):
    print(request.data)
    my_img = request.data['id_image']
    ima = Images.objects.get(id=my_img)
    print(self.id)
    print(self)
    flat = Flat.objects.get(id=7)
    flat.images.add(ima);
    serializer = FlatSerializer(flat, many=True)
    return Response("done")
    

''' '''

There are so many errors but I think I can make you clear有很多错误,但我想我可以让你清楚

First of all I would like to tell you about your view in general:首先,我想大致谈谈您的看法:

  • If you use CreateAPIView it using CreateModelMixin you should work with create method, not post, but it does not really matter ok.如果你使用CreateAPIView它使用CreateModelMixin你应该使用create方法,而不是发布,但这并不重要。
  • In CreateAPIView there is only post method so you can remove queryset attributeCreateAPIView中只有 post 方法,因此您可以删除queryset属性
  • Keep your view class thin and add your logic in serializer, create method in serializer in this case保持你的视图 class 薄并在序列化器中添加你的逻辑,在这种情况下在序列化器中create方法

And finally about your question.最后关于你的问题。 if your path url looks like this flat/<int:pk>/add-images then try this如果你的路径 url 看起来像这样flat/<int:pk>/add-images然后试试这个

lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
id = self.kwargs[lookup_url_kwarg]

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

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