Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 670
AdnanKattekaden Avatar asked Feb 01 '21 20:02

AdnanKattekaden


People also ask

How do I refer primary key in Django?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

Does Django support multiple primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

How do you get or view all the items in a model in Django?

The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.

What is the primary key in Django?

To know more about Primary key, visit here. The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one. If True, Django will store empty values as NULL in the database.

What is a foreign key in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it’s used to create many-to-one relationships within tables. It’s a standard practice in relational databases to connect data using ForeignKeys. What’s the difference between foreign key and primary key?

What is the PK lookup shortcut in Django?

) For convenience, Django provides a pk lookup shortcut, which stands for “primary key”. In the example Blog model, the primary key is the id field, so these three statements are equivalent:

How do I retrieve objects from the database in Django?

Django will complain if you try to assign or add an object of the wrong type. To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters.


Video Answer


3 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...

like image 106
Shaheen Hyder Avatar answered Oct 04 '22 21:10

Shaheen Hyder


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.

like image 35
Marco Avatar answered Oct 02 '22 21:10

Marco


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
like image 41
NKSM Avatar answered Oct 02 '22 21:10

NKSM