QuerySet:
https://www.w3schools.com/django/django_queryset.php
A QuerySet is a collection of data from a database.
<QuerySet [
<Members: Members object (1)>,
<Members: Members object (2)>,
<Members: Members object (3)>,
<Members: Members object (4)>,
<Members: Members object (5)>
]>
Views - init the API test views UI and also returns the processed API data
* Model returns queryset object data that's not JSON and can not be directly returned as response.
* Serailzer processes queryset data to dictonary and can be returned as JSON as HTTP response :
https://www.django-rest-framework.org/api-guide/serializers/
Serializing objects
We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class.
serializer = CommentSerializer(comment)
serializer.data
# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
For Views to call query set and make serailzier for the query set to return is redundant, hence, there is a mixin (a class which contains a combination of methods from other classes https://www.hackerearth.com/practice/notes/sachin/some-useful-mixins-in-django/#:~:text=In%20object%2Doriented%20programming%20languages,implemented%20as%20early%20as%20possible) called mixins.ListModelMixin
https://www.django-rest-framework.org/api-guide/generic-views/
For detail implementation check restframwork codebase:
https://github.com/encode/django-rest-framework
By default, when ListModelMixin is extended, the def list() function will be called and it will call get_queryset() to retreive queryset of the model and then calls seralizer to process that queryset to dictoanry then returns as in dictonary (JSON )
The implementation of the mixin is below :
https://www.django-rest-framework.org/api-guide/generic-views/
rest framwork code base :
https://github.com/encode/django-rest-framework
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAdminUser]
def list(self, request):
# Note the use of `get_queryset()` instead of `self.queryset`
queryset = self.get_queryset()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
To overwrite the queryset and extend mixin.ListModelMixin simply do :
class MyViewViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin):
serializer_class = serializers.PortalSerializer
# https://www.django-rest-framework.org/api-guide/authentication/
# Validate header: token: XXXXX
authentication_classes = (authentication.TokenAuthentication,)
# Permission to use API
# https://www.django-rest-framework.org/api-guide/permissions/
permission_classes = (permissions.IsAuthenticated,)
queryset = Portal.objects.all()
#Generivic Viewsets return get_queryset
# Instantiate to overwrite such as filtering etc
def get_queryset(self):
# Authenticated request will have authenticated user object
return self.queryset.filter(users=self.request.user.id).order_by('-name')
To completely overwrite including list function
https://stackoverflow.com/questions/49491705/how-to-modify-get-queryset-result-value
mixin.retreieveModelMixin:
RetrieveModelMixin
Provides a .retrieve(request, *args, **kwargs)
method, that implements returning an existing model instance in a response.
If an object can be retrieved this returns a 200 OK
response, with a serialized representation of the object as the body of the response. Otherwise it will return a 404 Not Found
.
https://stackoverflow.com/questions/46860183/django-rest-framework-how-retrieve-works
def get_object(self):
"""
Returns the object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
queryset = self.filter_queryset(self.get_queryset())
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
mixin.createModelMixin:
https://stackoverflow.com/questions/37537974/django-rest-framework-serializers-and-views
- mixins.CreateModelMixin - calling validate & create -> serializer.save -> serializer.create
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
perform_create(self, serializer)
- Called byCreateModelMixin
when saving a new object instance.perform_update(self, serializer)
- Called byUpdateModelMixin
when saving an existing object instance.perform_destroy(self, instance)
- Called byDestroyModelMixin
when deleting an object instance.
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
def perform_create(self, serializer):
serializer.save(user=self.request.user)
No comments:
Post a Comment