Yutong
Yutong

Reputation: 11

django return the most recent record of each user

I am learning django framework, and currently I am facing a problem.

There are two models

class User(models.Model):
    name = models.CharField(max_length=30)
    ...

class Action(models.Model):
    user = models.Foreign(User)
    action = models.CharField(max_length=30)
    createTime = models.DateTimeField(default=django.utils.timezone.now)

Each action from each user is inserted into Action Model, therefore, there are lots of records of each user in Action by different createTime.

Now, I would like to list the latest action of each user, but I have no idea to implement it.

Upvotes: 1

Views: 523

Answers (2)

Ivan
Ivan

Reputation: 2675

Try something like:

from django.db.models import F, Max


actions = Action.objects.annotate(
    most_recent=Max('user__action__createTime')
).filter(createTime=F('most_recent'))

Upvotes: 3

NS0
NS0

Reputation: 6096

You can query Action with the user you want info on, like this

actions = Action.objects.filter(user=selected_user).order_by("-createTime")

This will sort user actions by date in descending order, to get the latest action:

actions.first()

Upvotes: 0

Related Questions