Samat Sadvakasov
Samat Sadvakasov

Reputation: 639

How to get last record of current active user?

I need to take a last record which user uploaded to DB. I know how to find last one, it is easy(Documents.objects.last()). But I am not sure it's right, cause in same time another user can upload a file, so I will get his record. Here is my code:

models.py

from django.db import models

class Document(models.Model):
    username = models.CharField(max_length=100, blank=True, null=True)
    document = models.FileField(upload_to='documents/%Y/%m/%d/%H:%M:%S')
    uploaded_at = models.DateTimeField(auto_now_add=True)

tabu.py

from .models import Document

class TabuName:
    def tabufunction(self):
        res = Document.objects.last()
        return res

I can't use request.user.username in that file. I've read that it is not good practice in django. Do you know a solution of this problem?

Upvotes: 0

Views: 68

Answers (2)

Hayden
Hayden

Reputation: 459

first,you can change username to ForeignKey of User model

user = models.ForeignKey(User,on_delete=models.CASCADE)

In normal the currency problem can be ignored.If you care about it,you can store last user info in cachedb,for example:Redis.

Upvotes: 3

echefede
echefede

Reputation: 536

res = Document.objects.filter(username=request.user.username).order_by('-id')[0]

Upvotes: 0

Related Questions