Help me please with my problem. I want to get objects sorted first by one filter and then by another filter.
How can I get objects with this ordering in 1 query to the DB (need for pagination)?
This example shows queryset without ordering:
rooms = Room.objects.filter(Q(name__icontains=search) | Q(owner__username__icontains=search))
I have the room model:
models.py
from django.db import models
from django.contrib.auth.models import User
class Room(models.Model):
name = models.CharField(max_length=150)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
views.py (my bad code)
class RoomListView(ListAPIView):
def get_queryset(self):
search = 'test' # for example
rooms1 = Room.objects.filter(owner__username__icontains=search)
rooms2 = Room.objects.filter(name__icontains=search)
return list(rooms1) + list(rooms2)
The wrong result: search = "test"
[
{
"id":1,
"name":"test",
"owner":{
"username":"user1"
}
},
{
"id":2,
"name":"room1",
"owner":{
"username":"test"
}
},
{
"id":3,
"name":"test2",
"owner":{
"username":"user2"
}
}
]
The correct result: search = "test"
[
{
"id":2,
"name":"room1",
"owner":{
"username":"test"
}
},
{
"id":1,
"name":"test",
"owner":{
"username":"user1"
}
},
{
"id":3,
"name":"test2",
"owner":{
"username":"user2"
}
}
]
How can I get objects with this ordering in 1 query to the DB (need for pagination)?