Alternatively, you can use multiple table inheritance and include common attributes in the superclass model. Then you simply order_by load the date into the superclass model. The third-party application django-model-utils provides a custom manager called Inheritance manager that allows you to automatically disable subclass models in your request.
from model_utils.managers import InheritanceManager class MediaItem(models.Model): objects = InheritanceManager() user = models.ForeignKey(User) upload_date = models.DateTimeField(auto_now_add=True) title = models.CharFiled(max_length=1000, blank=True) class ImageItem(MediaItem): image = models.ImageField(upload_to=img_get_file_path) class VideoItem(MediaItem): video = models.FileField(upload_to=vid_get_file_path) class AudioItem(MediaItem): audio = models.FileField(upload_to=aud_get_file_path)
Then your query looks simple:
MediaItem.objects.all().order_by('upload_date').select_subclasses()
This way you get what you want with one query (with three joins). In addition, your data is better normalized, and it is quite simple to support all kinds of more complex queries, as well as pagination.
Even if you do not, I would still use the abstract inheritance of the base class to conceptually normalize your data model, although you do not get the benefits of a database and ORM.
source share