Jshee
Jshee

Reputation: 2686

Django Retrieve last 10 records for a given query

I was reading the django documentation, and thought this would work to limit to resulting query results to the last 10 results, but it isnt doing that.

Here my db query:

TSUH = TSUH.objects.filter(FKToUser_id=request.user).all()[10:]
    TSFH = TSFH.objects.filter(FKToUser_id=request.user).all()[10:]
    TSJH = TSJH.objects.filter(FKToUser_id=request.user).all()[10:]

    return render(request, page.html', {
         'GivenTSUH':TSUH

    })

my template contains:

    {% if TSUH %}
        {% for T in TSUH %}
            <li>{{ T.scanBegin }}<span> to <span>{{ T.begin }}</span> </li>
        {% endfor %}
    {% else %}
        It appears there are no results.
    {% endif %}

This is returning a lot more than 10 results for each query. is the all() throwing it off?

Thoughts? Thanks

Upvotes: 0

Views: 287

Answers (2)

shafikshaon
shafikshaon

Reputation: 6404

You can try this

TSFH = TSFH.objects.filter(FKToUser_id=request.user).all().order_by('-pk').[:10]
TSJH = TSJH.objects.filter(FKToUser_id=request.user).all().order_by('-pk').[:10]

This will give 10 last inserted records.

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47364

You are using incorrect syntax. It should be number after : not before. Also you can use reverse to change query ordering, like this:

TSUH = TSUH.objects.filter(FKToUser_id=request.user).reverse()[:10]

Upvotes: 1

Related Questions