Home > database >  ordering is not working with django model seralizer
ordering is not working with django model seralizer

Time:01-05

I am using 2.2.16 django versiong and 3.11.2 django_rest_framework version and using serializers.ModelSerializer CRUD operation is working but ordering is not working.

models.py code is below,

class Ticket(models.Model):
    title = models.CharField(max_length=255)
    description = models.CharField(blank=True, max_length=255)
    notes = models.TextField()

eg: code in seralizers.py

from rest_framework import serializers

class Ticket(serializers.ModelSerializer):
    title = serializers.CharField()
    description = serializers.CharField(required=False)
    notes = serializers.CharField(required=False)

class Meta(object):
    fields = '__all__'
    depth = 1
    model = Ticket
    ordering_fields = ["title"]

def __init__(self, *args, **kwargs):
    super(Ticket, self).__init__(*args, **kwargs)

When i do GET operation as below, ordering is not working with query parameters

eg:

http://localhost:4200/api/ticket?ordering=title

Above api call is returning add data with default ordering as ID (auto created field), but not returning in the assenting of title field (which is a char field).

How can I fix this? Also how can i add filtering to the same

eg: http://localhost:4200/api/ticket?title=abc  # this should give me result of only matching title field with abc or starts with abc 

CodePudding user response:

If you want to set a default ordering for you model, you can do it in your model's Meta class:

class Ticket(models.Model):
    ...
    class Meta:
        ordering = ["title"]

As docs says in Django Docs

Or, you can do the sorting in your ListView, you can see it in SO.

But if you want to have filter and search in your api, you should declare ordering_filters and search_fields in you view. Read about it in DRF Docs

  • Related