Amanpreet Singh
Amanpreet Singh

Reputation: 73

Sort a list of queryset objects from different models by the date_created attribute of object

I have different models all of which have a 'DateTimeField' named 'date_created'. I need to select all objects from all models, sort them by this field 'date_created' and return as a list.

I have tried the following:

models.py

class FirstModel(models.Model):
    title = models.CharField(max_length=100)
    date_created = models.DateTimeField()


class SecondModel(models.Model):
    title = models.CharField(max_length=100)
    date_created = models.DateTimeField()

views.py

def browse(request):
    object_list = []
    for model in get_models(get_app('myapp')):
        object_list.append(model.objects.order_by('-date_created').all())
    object_list = sorted(object_list, key=attrgetter('date_created'))
    context = {'data': object_list}
    return render(request, 'myapp/browse.html', context)

I get the error 'QuerySet' object has no attribute 'date_created'.

These models have other fields irrelevant to this question. I can use a common base class for getting all objects together(I suppose) but I'm using an abstract base class for some reason. I suspect 'joins' could be used but I've no idea how to do that.

So, how can I sort this object_list (which is a list of objects from different models) by date_created attribute?

Upvotes: 2

Views: 5516

Answers (2)

Romans 8.38-39
Romans 8.38-39

Reputation: 456

I think you should replace this code

object_list.append(model.objects.order_by('-date_created').all())

with this code :

object_list.append(model.objects.all().order_by('-date_created'))

And I think you don't need to use this code

object_list = sorted(object_list, key=attrgetter('date_created'))

Because you've sorted already using "order by"

Upvotes: 1

Amanpreet Singh
Amanpreet Singh

Reputation: 73

I found the answer with some more research.

The problem is in this line:

object_list.append(model.objects.order_by('-date_created').all())

While I am using "append", it is treated as a normal list rather than a list of queryset objects { I'm a bit unsure about this, basically this line gives me a list of lists where I need just a list of all the queryset objects. } To correct this chain() from itertools can be used by importing chain and replacing above line as shown below:

from itertools import chain
...
...
object_list = chain(object_list, (model.objects.order_by('-date_created').all()))
...

Rest everything is fine. Also, as its pointed out in question, multi table inheritence could be used which can get all results sorted in a single query by using order_by

Upvotes: 4

Related Questions