How to filter the last entry registered by your user id - Django

1

Hello friends, I'm new to django. I would like to make a query to update the number field.

What I want to do is filter by the user and filter by the last entry of that user, and then update the number field.

The querysets I know are the following, but I do not know how I could implement them to make the query:

Model.objects.latest('x')
Model.objects.filter()

My model is as follows:

models.py

class Model(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    id = models.AutoField(primary_key=True)
    number = models.FloatField(default=0)
    created = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        ordering = ['-created']

With the class Meta I ordered the records for the most recent, but now how I could access the last record to update it.

Thank you very much friends!

    
asked by Yamamoto AY 23.08.2018 в 06:42
source

2 answers

1

Assuming you want to filter by the user id:

instance = Model.objects.filter(user__id=5).first()

or by the user's first name:

instance = Model.objects.filter(user__first_name='Pedro').first()

or by the last name:

instance = Model.objects.filter(user__last_name='Torres').first()

The way you have your ordering uses first() , if you remove that ordering condition you should use last() . With this you can now edit the value of number with instance.number = numero_flotante and save it with instance.save()

    
answered by 28.08.2018 / 02:09
source
1

The result of all the objects ordered by date is saved in a list, you can access the first element which should be the one with the most recent date: ultimo = Model.objects.all()[0] or you can access not only the last one but 4 0 Last 5, example ultimo = Model.objects.all()[0:4] , ultimo = Model.objects.all()[0:5]

    
answered by 23.08.2018 в 07:01