CodeSpent
CodeSpent

Reputation: 1904

Get multiple models in single QuerySet ordered by timestamp

I'm working on a table consisting of all events performed on a user despite that these events are represented by 4 different models.

The models are:

I want these to all be visible to the user in their dashboard, but in a single table ordered by timestamp. I could do a single query for each model then append to a dictionary which I'll then sort by date, however, I don't want to go against a native solution if there is one (and I don't believe this is an edge case so I could foresee it).

Is there a native way of retrieving multiple models in a single QuerySet?

Upvotes: 0

Views: 147

Answers (1)

Ozgur Akcali
Ozgur Akcali

Reputation: 5492

There is no native way to retrieve multiple un-related models in a single QuerySet. What you can do is to use model inheritance, have a base model for all event models. With the following model structure;

class Event(models.Model):
    timestamp = models.DateTimeField()
    user = models.ForeignKey(User)
    ...

class WebhookSubscription(Event):
   ...

class WebhookEvent(Event):
   ...

class TokenRefresh(Event):
   ...

class LogEvent(Event):
   ...

You can query directly using the Event model like;

events = Event.objects.filter(user=user).order_by('timestamp')

This would give you Event instances, which won't hold data for child models. You can get the child instance from a parent just like following a OneToOneField (thats how django hadnles model inheritance actually, creating two tables and linking them with a foreign key):

event.webhooksubscription
event.webhookevent
event.tokenrefresh
event.logevent

These would return child model instances if exists, and raise an ObjectNotFound exception if the parent does not have a related specified child model instance.

This approach would let you do operations like sorting and slicing at the database level, with the downside of added model complexity (You'll need a separate query to get child model data)

Upvotes: 1

Related Questions