简体   繁体   中英

how to get id of current object

how to get current id instead of static id (7) to add image to flat

'''

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.
  • In CreateAPIView there is only post method so you can remove queryset attribute
  • Keep your view class thin and add your logic in serializer, create method in serializer in this case

And finally about your question. if your path url looks like this flat/<int:pk>/add-images then try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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