0

I have three django models and I want to get CRUD logs. I have merged queryset and sorted them based on object creation date (createdtstamp field). I am using django-simple-history stores Django model state on every create/update/delete.

player = Player.history.all().values('first_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp')
coach = Coach.history.all().values('coach_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp')
title = Title.history.all().values('title_name',  'history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp')

#merge queryset and sort based on createdtstamp

result_list = sorted(chain(player, coach, title), key=lambda instance: instance.createdtstamp)

queryjson  = json.dumps(result_list, cls=DjangoJSONEncoder)

return HttpResponse(queryjson)

Above merge and sort doesn't seem to work!

How can I sort query result based on createdtstamp field (sort by latest)?

Similar question have been asked before Display objects from different models at the same page according to their published date

But my question is different as Player.history.select_related doesn't have Coach and Title fields.

Player.history.select_related('Coach', 'Title').all().order_by('-createdtstamp').

Community
  • 1
  • 1
MysticCodes
  • 3,092
  • 5
  • 25
  • 33
  • you can use Q objects for filtering.....for more details you can go here [Complex lookups with Q objects](https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q-objects) – Amrit Dec 22 '16 at 10:12
  • 2
    It's not clear what your question is - your code already appears to merge and sort the querysets in the line `result_list = sorted(...)`. – Alasdair Dec 22 '16 at 10:12
  • Possible duplicate of [Display objects from different models at the same page according to their published date](http://stackoverflow.com/questions/37747427/display-objects-from-different-models-at-the-same-page-according-to-their-publis) – e4c5 Dec 23 '16 at 09:26
  • @e4c5 - I have createdtstamp on each model. I am trying to get CRUD logs of each models based on createdtstamp. Previous duplication link pointer was helpful though. – MysticCodes Jan 02 '17 at 08:32

0 Answers0