Home > other >  How to sort list in DRF?
How to sort list in DRF?

Time:11-08

I've got two models with onetoone relation user and blog. While listing users I want to have users with blog on top. How to order users so that users with blog is on first of list and secondary order by users id? My Models:

class User(BaseModel):
    name = models.CharField(max_length=100)

class Blog(BaseModel):
    user = models.OneToOneField(User, related_name='blog', null=True)
    title = models.CharField(max_length=100)

My view:

class UserAPIView(ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

CodePudding user response:

You can work with an Exists subquery with:

from django.db.models import Exists, OuterRef

class UserAPIView(ListAPIView):
    queryset = Movie.objects.order_by(
        Exists(Blog.objects.filter(user_id=OuterRef('pk'))).desc()
    )
    serializer_class = UserSerializer

We thus determine for each User if there is a Blog for that User, and we sort true before false by making use of the .desc(…) method [Django-doc].

  • Related