Question

Say I have 3 models (Blog, News, Photos) and i want to get the latest 3 pieces of content regardless of which model they belong to.

With (psuedo) sql I could do something like:

SELECT * 
FROM blog, news, photo, 
WHERE is_published=True
ORDER by publication_date
LIMIT 3  

I don't really want to use to use raw sql in Django as i want a query set returned, so is there a way I can make this type of query with Django?

Thanks,

Was it helpful?

Solution

If the 3 models are similar in some way (as they appear to be), the way I would probably do it is by creating a base model and then have the 3 other models inherit from that model.

class Publishable(models.Model):
    is_published = models.BooleanField(default=False)
    publication_date = models.DatetimeField()
    ... other fields ...

class Blog(Publishable):
   ...extra fields...

class News(Publishable):
   ...extra fields...

class Photos(Publishable):
   ...extra fields...

Then later on, you can do:

Publishable.objects.order_by('-publication_date')[:3]

If you still need the "type" associated with the retrieved models, check out the Inheritance Manager

You'll probably want to read about the pros and cons about Model Inheritance as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top