1
votes

So let's say I have the following models in Django:

class Review(models.Model): 
    datetime = models.DateTimeField(("Date"), default=timezone.now)

class Rating(models.Model): 
    datetime = models.DateTimeField(("Date"), default=timezone.now)

And my view looks like this:

def get_page(request, id_slug):
    context_dict = {}
    reviews = Review.objects.filter(attribute=id_slug).order_by('-datetime')
    ratings = Rating.objects.filter(attribute=id_slug).order_by('-datetime')
    context_dict['reviews'] = reviews
    context_dict['ratings'] = ratings
return render(request, 'page.html', context_dict)

What I want to do is make a query set that would include both Review and Rating objects, ordered by the datetime attribute, so something like:

activity =  reviewsANDratings.order_by('-datetime')
context_dict['activity'] = activity

What would be the best way to achieve this?

Thank you!

1

1 Answers

0
votes

If your models are basically the same thing, or parent/child of one another, consider using Django polymorphic, which will let you get all the Reviews and Ratings in one PolymorphicQuerySet.

For more disparate models, (or for simpler implementation), just do two queries, like you are now, and merge the items in Python like so:

reviews_and_ratings = sum([list(reviews), list(ratings)], [])
reviews_and_ratings.sort(key=lambda item: item.datetime, reverse=True)
context_dict['reviews_and_ratings'] = reviews_and_ratings