Home > Enterprise >  Django REST API Query to return 2 value
Django REST API Query to return 2 value

Time:09-20

I am a beginner who is learning Django using wagtail. I have a custom API model where I need to do 2 queries. I tried to return 2 queries at the same time with this code

def get_queryset(self):
        return super().get_queryset().order_by('-first_published_at'), super().filter_queryset('story_type=Story')

and I am getting Attribute error 'str' object has no attribute 'model'

Here is my api.py

class ProdPagesAPIViewSet(BaseAPIViewSet):
    renderer_classes = [JSONRenderer]
    filter_backends = [FieldsFilter,
        ChildOfFilter,
        AncestorOfFilter,
        DescendantOfFilter,
        OrderingFilter,
        TranslationOfFilter,
        LocaleFilter,
        SearchFilter,]
    meta_fields = ["type","seo_title","search_description","first_published_at"]
    body_fields = ["id","type","seo_title","search_description","first_published_at","title"]
    listing_default_fields = ["type","seo_title","search_description","first_published_at","id","title","alternative_title","news_slug","blog_image","video_thumbnail","categories","blog_authors","excerpt","content","content2","tags","story_type"]
    nested_default_fields = []
    def get_queryset(self):
        return super().get_queryset().order_by('-first_published_at'), super().filter_queryset('story_type=Story')
    name = "stories"
    model = AddStory

api_router.register_endpoint("stories", ProdPagesAPIViewSet)

With the order_by I am getting newest published stories first But I also want to filter story_type=Story. If I query this using URL then it works fine like ?story_type=Story

Here is the API response with the order_by query

{
  "id": 5,
  "meta": {
    "type": "blog.AddStory",
    "seo_title": "",
    "search_description": "",
    "first_published_at": "2022-09-19T23:27:12.895017Z"
  },
  "title": "Test Story",
  "alternative_title": "Alternative Heading",
  "blog_image": {
    "id": 1,
    "meta": {
      "type": "wagtailimages.Image",
      "detail_url": "http://localhost/api/v2/images/1/",
      "download_url": "/127.0.0.1/media/original_images/tiktok_U4POKiL.jpeg"
    },
    "title": "tiktok"
  },
  "excerpt": "Test Excerpt",
  "content": "<div class=\"block-full_richtext\"><p data-block-key=\"h053a\"> Test Story </p></div>",
  "tags": [
    "Test"
  ],
  "news_slug": "eea1awauwc",
  "story_type": "Story"
} 

What I want is to filter story_type=Story & order_by('-first_published_at') at a same time, How can I do that?

Thanks a lot for reading.

CodePudding user response:

def get_queryset(self):
        return super().get_queryset().filter('story_type=Story').order_by('-first_published_at')
  • Related