[Answer]-How to fetch and display data from 2 models in a single queryset ordered by time, Django

1πŸ‘

βœ…

The most simple way of archiving this is to have a base model, call it Base_event,

class Base_event(models.Model):
     user = models.ForeignKey(User_info)
     created = models.DateTimeField(auto_now_add=True)

and derive both your models from this Base. This way you write less code, and you archive your objective. Notice that you have to make an implementation choice: how will they will inherit from base. I advice to read Django documentation to help you choose wisely according to what you want to do.

EDIT:

I would notice that the accepted answer has a caveat. It sorts the data on the python and not on the mysql, which means it will have an impact on the performance: the whole idea of mysql having SORT is to avoid having to hit the database and them perform the sorting. For instance, if you want to retrieve just the first 10 elements sorted, with the accepted solution you have to extract all the entries, and only then decide which ones are the first 10.

Something like Base_event.objects.filter().sort_by(…)[10] would only extract 10 elements of the database, instead of the whole filtered table.

The easy solution now becomes the problem later.

πŸ‘€Jorge Leitao

0πŸ‘

Try something like creating list chain.

feed = list(chain(User_image,User_status))
feed = sorted(feed, key=operator.attrgetter('date_added'))

for those who refer it as not correct.
https://stackoverflow.com/a/434755/2301434

Leave a comment