문제

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,

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top