How to get next available object or primary key from database in django

Viewed 827

I am trying for a music player and i want to get next music from database with current music's id. So if anyone could tell how to get next primary key with current id.

This is the code for getting current music.

music = Contents.objects.get(id=id)

The id that I passed is primary key of current music. So instead of the code above please do suggest how can I get next music.

4 Answers

I will suggest you a simple solution. If you are fetching the object by id+1 then if a element is removed then it will cause error.

So just filter with id greater than the current id and take the first one.

music= Contents.objects.filter(id__gt=id).order_by('id').first()
if music is None:
    music= Contents.objects.all().order_by('id').first()

The else condition is to pick up 1st music if the current music is last one. Below I will just mention how to pick previous music

music= Contents.objects.filter(id__lt=id).order_by('id').last()
if music is None:
    music= Contents.objects.all().order_by('id').last()

Hope it will solve your problem...

You can use iterator():

q = Contents.objects.filter(id__gt=current_music_object.id)
next(q.iterator())

Provided that these are correctly sorted. Or you can use queryset slicing:

next_music_object = Contents.objects.filter(id__gt=current_music_object.id)[0]

This will also work if you have removed some ID's in between.

You can use django Pagination - see The Paginator class

Then you can do something like this:

from django.core.paginator import Paginator
from django.shortcuts import render

def contentsList(request, template_name="music.html"):
    data = {}
    music = Contents.objects.order_by('-pk')

    paginator = Paginator(querySet, 1)
    # get your page from GET
    page = request.GET.get('page')
    data[page_obj] = paginator.get_page(page)
    return render(request, template_name, data)

and in your template you can do like this:

{% for music in page_obj %}
    
    {{ music.title }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>

Give Paginator a list of objects, plus the number of items you’d like to have on each page, and it gives you methods for accessing the items for each page:

>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)

>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)

>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']

>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True

Just add a +1 to it so the value is increased and you get the next object.

next_music = Contents.objects.get(id=id+1)
Related