Skip to content Skip to sidebar Skip to footer

How Do I Collect Multiple Django Models Together Into A Single List?

I have a fairly straightforward blog in Django, with separate models for Article and Link. I want to have a loop in my template that lists them both in date order, which means some

Solution 1:

Turns out the solution is to turn the abstract class into a real one, and then I can collect over that.

Solution 2:

Well, the obvious answer would have been to make Post a concrete class. Else you'll probably have to squeeze the ORM and resort to handcoded SQL or manually merge/order your two querysets. Given the small size of the dataset, I'd go for this last solution.

Solution 3:

Refactoring could be the better solution, but here is another one that could do the job:

Create a custom Manager:

classPostManager(models.Manager):
    defmixed(self, first):
        all_dates = []
        articles_dates = Articles.objects.extra(select={'type':'"article"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        links_dates = Links.objects.extra(select={'type':'"link"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        all_dates.extend(articles_dates)
        all_dates.extend(links_dates)
        # Sort the mixed list by post_date, reversed
        all_dates.sort(key=lambda item: item['post_date'], reverse=True)
        # Cut first 'first' items in mixed list
        all_dates = all_dates[:first]
        mixed_objects = []
        mixed_objects.extend(Articles.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'article']))
        mixed_objects.extend(Links.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'link']))
        # Sort again the result list
        mixed_objects.sort(key=lambda post: post.post_date, reverse=True)
        return mixed_objects

And use it in your abstract model:

classPost(models.Model):

    classMeta:
        abstract = Trueobjects= PostManager()

Then the call for your mixed objects will be:

Article.objects.mixed(10)

Post a Comment for "How Do I Collect Multiple Django Models Together Into A Single List?"