7π
I would use ViewSet as oppose to ModelViewSet. The code below should do what you need unless there is a strong reason to use ModelViewSet. If you go to the URL of say http://yourdomain/yourmodel/10
the pk variable will have a value of 10.
class YourModelViewSet(viewsets.ViewSet):
def retrieve(self,request,pk=None):
u = request.user
queryset = YourModel.objects.filter(user=u,pk=pk)
if not queryset:
return Response(status=status.HTTP_400_BAD_REQUEST)
else:
serializer = YourModelSerializer(queryset)
return Response(serializer.data,status=status.HTTP_200_OK)
Thanks β Hope it helps
- [Django]-Why does manage.py execution script run twice when using it under if __name__ == "__main__"
2π
Since youβre using viewsets.ModelViewSet
Django Rest Framework handles all the filtering of specific objects for you. Change your queryset
property to MyObjects.objects.all()
.
Overriding queryset
as others suggested will break the /myObjects/
route because the id
does not exist.
- [Django]-How to use a different database for Heroku review apps?
- [Django]-Django slug field in Arabic and other foreign languages
- [Django]-Thumbnails in the django admin panel using sorl
- [Django]-Insert pandas data frame into Postgres
- [Django]-Django 2 upgrade lost filter_horizontal functionality
2π
If you want (or need) to stick with viewsets.ModelViewSet
, you can still access the id from the kwargs
argument of the action methods.
class MyObjectViewSet(viewsets.ModelViewSet):
def update(self, request, *args, **kwargs):
obj_id = kwargs['pk']
obj = MyObject.objects.get(pk=obj_id)
# Do your thing
# Send back response
- [Django]-ImportError: cannot import name connections
- [Django]-Using Requests python library to connect Django app failed on authentication
0π
Your logger line is referencing self, but there is no self in that context (you are at class level, not inside a method). Try removing the logger line.
- [Django]-ValueError: Related model u'mutech.branch' cannot be resolved
- [Django]-Apache + Django on Windows does not start
- [Django]-Crontab is running but still not executing command Django
- [Django]-Django: How do you access a model's instance from inside a manager?