Reputation: 1313
I have this model:
class LogBook_audit(models.Model):
id = models.AutoField(primary_key=True)
logbook = models.ForeignKey(LogBook, verbose_name='Logbook Control No.')
username = models.ForeignKey(User, null=True, blank=True, verbose_name='Username')
status = models.CharField(null=False, blank=False, max_length=40, choices=STATUS_TYPE, default=u'CHECKING REQUIREMENTS', verbose_name='Status')
log_in = models.DateTimeField(default=lambda:datetime.now(), verbose_name='Work start')
I'm trying to create a queryset to find latest user who log_in for such specific logbook and status.
undolink(request, pk):
undo_rec = LogBook.objects.get(pk=pk)
latest_user = LogBook_audit.objects.filter(logbook_id=pk, status=undo_rec.status).aggregate(Max('log_in'))
...
But latest_user is giving me a latest log_in format. I was thinking I can used latest_user.username
but failed. Is there a way to find that username? Any guide is really appreciated.
Upvotes: 4
Views: 6801
Reputation: 14180
You can use latest()
instead:
latest_log = LogBook_audit.objects.filter(logbook_id=pk, status=undo_rec.status).latest('log_in')
then you can access user through latest_log.user
.
Upvotes: 9
Reputation: 8623
You want to get a queryset result, so you should use annotate()
:
latest_user = (LogBook_audit.objects
.filter(logbook_id=pk, status=undo_rec.status)
.annotate(max_log_in=Max('log_in')))
Hope it helps.
Upvotes: 1