0

I am using wagtail. I have serialized my API. I want to order them by -first_published_at, when someone hit my API url api/v2/pages they will see an ordered API without filtering it via URL. here is my api.py code:

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",]
    nested_default_fields = []
    ordered_queryset= [] 
    name = "pages"
    model = AddStory

api_router.register_endpoint("pages", ProdPagesAPIViewSet)

I have tried ordered_queryset= [AddStory.objects.order_by('-first_published_at')]

But it's not ordered by the newest published stories. How should I do the query?

Here is my API response

{
  "meta": {
    "total_count": 6
  },
  "items": [
    {
      "id": 4,
      "meta": {
        "type": "blog.AddStory",
        "seo_title": "",
        "search_description": "",
        "first_published_at": "2022-08-30T11:05:11.341355Z"
      },
    {
      "id": 6,
      "meta": {
        "type": "blog.AddStory",
        "seo_title": "",
        "search_description": "",
        "first_published_at": "2022-08-30T11:13:47.114889Z"
      },
{
  "id": 7,
  "meta": {
    "type": "blog.AddStory",
    "seo_title": "",
    "search_description": "",
    "first_published_at": "2022-08-31T11:13:47.114889Z"
  },

1 Answers1

0

Solved after using get_queryset instead of order_queryset #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",]
    nested_default_fields = []
    def get_queryset(self):
        return self.model.objects.all().order_by("-first_published_at")
    name = "pages"
    model = AddStory

api_router.register_endpoint("pages", ProdPagesAPIViewSet)