开发者

Django : How to retrieve latest object created

开发者 https://www.devze.com 2023-04-12 16:55 出处:网络
I want to retrieve the latest object created for a particular user. Let\'s say I have a model: class LogBookPreTransaction(models.Model):

I want to retrieve the latest object created for a particular user.

Let's say I have a model:

class LogBookPreTransaction(models.Model):
    person = models.ForeignKey(User)
    code = models.CharField(max_length=20)
    address = models.CharField(max_length=200,null =True)
    pincode = models.CharField(max_length=20,null =True)

Now I want to retrieve the latest object created for a user = "X". How can we do that?

transaction_obj = LogBookPreTransaction.objects.filter(user = "x")开发者_如何学运维.latest()

Off course this won't work, but I want something like this. Is the question clear?


You can use latest only if you have a date field, which you have so try:

LogBookPreTransaction.objects.filter(user = "x").latest('datetime')

Try also this, it can be useful when you don't have a date field:

LogBookPreTransaction.objects.filter(user = "x").order_by('-id')[0]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号