How can you merge querysets in Django? I use the Django Rest Framework.
I work with the following model:
class City(models.Model):
...
class House(models.Model):
city = models.ForeignKey(City, ...)
...
class Resident(models.Model):
house = models.Foreignkey(House, ...)
...
I now want to have a view that lists all the residents of a given city (slug is the slug of the city).
Here is how I wrote it:
class ResidentList(generics.ListAPIView):
lookup_field = 'slug'
serializer_class = ResidentSerializer
permission_classes = (IsAuthenticated, IsMayor)
def get_queryset(self):
residents = Resident.objects.filter(house__city__slug=self.kwargs['slug'])
return residents
As you can see I create the list of residents for a city by iterating through all the citizens and filter those who life in a home that lifes in the right city. I just feel like this is pretty bad and inefficient, since the database has to loop through ALL the citizens. It would be better to have something like
City.objects.get(slug=<cityslug>).houses.residents
Then I would only have to loop through the smaller amount of cities. The problem with this obviously is that the above query returns a queryset. Therefore I can't chain houses and residents like that.
PS: If you have other suggestions how I can improve my view let me know!
PPS: I found this question here on stackoverflow, but it only shows how to get a list, which wouldn't work with get_queryset and the django rest structure, would it?
Edit (More specification to get the question better): So the goal is to hit the api route:
localhost:8000/api/house/<city_slug>/residents/
And get a list of all the residents in the city.
Like this:
{
[
{
resdidentid = "<some_resident_id>",
residentname = "<some_resident_name>",
...
},
{
resdidentid = "<some_resident_id>",
residentname = "<some_resident_name>",
...
},
{
resdidentid = "<some_resident_id>",
residentname = "<some_resident_name>",
...
},
...
]
}