1

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
Avik Pradhan
  • 85
  • 1
  • 10
  • Does this answer your question? [Django: Adding "NULLS LAST" to query](https://stackoverflow.com/questions/15121093/django-adding-nulls-last-to-query) – Harun Yilmaz Nov 07 '21 at 15:37

1 Answers1

1

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].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555