'get last instance of model which contains request.user in manytomanyfield

I am building a BlogApp and I am trying to get the last instance of model in which request.user in ManyToManyField

I have tried using

models.py

class Blog(models.Model):
    title = models.CharField(max_length=3000)
    likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_likes')

views.py

def get_data(request):
    get_last_blog = Blog.objects.filter(likes__in=[request.user]).last()

    print(get_last_blog)

But it is showing first instance not last. I have tried without list like likes__in=request.user but it shows

'User' object is not iterable

I have tried many times but it is still not working. I am new in django. Any help would be much Appreciated. Thank You in Advance



Solution 1:[1]

.last() gets last or None object from queryset, so it's based on your order_by. I think you should be using .latest('<your_timestamp_field') and it will get latest object based on that timestamp field. Remember that .latest() can raise ObjectDoesNotExist exception if queryset is empty

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TrueGopnik