Logo

dev-resources.site

for different kinds of informations.

Django API | queryset & object, filter() & get()

Published at
11/28/2024
Categories
drf
Author
hyun_hyun
Categories
1 categories in total
drf
open
Author
9 person written this
hyun_hyun
open
Django API | queryset & object, filter() & get()

I tried this unittest.

    def test_price_of_photo_list(self):
        photo1 = create_photos()
        create_prices(photo1)

        url = detail_url(photo1.id)
        res = self.client.get(url)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
Enter fullscreen mode Exit fullscreen mode

and I got an error.

TypeError: 'Photos' object is not iterable
Enter fullscreen mode Exit fullscreen mode

First, Let's go to the views.py.

class PhotoDetailView(generics.ListAPIView):
    serializer_class = PhotoDetailSerializer

    def get_queryset(self):
        queryset = Photos.objects.get(id=self.kwargs['photo_id'])
        return queryset
Enter fullscreen mode Exit fullscreen mode

I wrote a Photo object. It could be cause.

  • .get(): returns a object.
  • .filter(): returns a queryset.

OK. We can't return a object to run. Then why?

ListAPIView expects a queryset. (not a object)
In documents,

ListAPIView
Used for read-only endpoints to represent a collection of model instances.
Provides a get method handler.
Extends: GenericAPIView, ListModelMixin

Move to GenericAPIView and ListModelMixin.

GenericAPIView
This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views.
Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.
Attributes
Basic settings:
The following attributes control the basic view behavior.
queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

ListModelMixin
Provides a .list(request, *args, **kwargs) method, that implements listing a queryset.
If the queryset is populated, this returns a 200 OK response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.

As you can see two api expect queryset. Then what I can modify?

  • .filter(): returns a queryset.

Let's change the method to filter.

class PhotoDetailView(generics.ListAPIView):
    serializer_class = PhotoDetailSerializer

    def get_queryset(self):
        queryset = Photos.objects.filter(id=self.kwargs['photo_id'])
        return queryset
Enter fullscreen mode Exit fullscreen mode

Wow, it works! I'm happy

drf Article's
30 articles in total
Favicon
Djoser+SimpleJWT
Favicon
AssertionError: 403
Favicon
extra_kwargs arguments
Favicon
To Django or to DjangoREST?
Favicon
Django API | queryset & object, filter() & get()
Favicon
I just tried to compare values between model and serializer
Favicon
Customize Schema with @extend_schema_view
Favicon
Seperate serializers
Favicon
Leveraging Headers for Dynamic Localization in Django
Favicon
Django REST Framework warning: `UnorderedObjectListWarning`
Favicon
DRF create @property decorator in view and use property in serializer
Favicon
why Serializers used for? easy to understand
Favicon
Async API Calls Unleashed: Exploring Django 4 and Django Rest Framework
Favicon
# Comprehensive Security for Class-Based Views in Django Rest Framework
Favicon
HATEOAS Principle - Generating Full Paths for Objects in Django Rest Framework.
Favicon
Instance version control in DRF with Django Reversion
Favicon
Django News #171 - DjangoCon US 2023 Preview
Favicon
How to create thumbnails programmatically in Django
Favicon
Automatically Add Logged In User Under 'created_by' and 'updated_by' to Model in Django Rest Framework
Favicon
how to fix raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
CSRF verification failed. Request aborted. in django rest framework
Favicon
How to fix "Must supply api_key"
Favicon
Updating A Many-To-Many Relationship In Django
Favicon
Excluding Fields in Django Rest Framework Serializers
Favicon
JWT Authentication with Django REST Framework - What? Why? How?
Favicon
How to implement Auto Expiring Token in Django Rest Framework
Favicon
Building web applications with Django, Django REST Framework and Nuxt
Favicon
How to use Postman to authenticate to Django Rest Framework
Favicon
Setting Up Django Rest Framework

Featured ones: