Sort list with Python + Django

Asked

Viewed 1,396 times

1

Good afternoon guys, I have a problem, register by the Django admin a video that should be sent to my template, however I need these videos to be ordered by the field position that I have in my models.py that I’m on the bench

py.models:

from django.db import models

class Video(models.Model):
    url = models.CharField(max_length=500, verbose_name='Link Embed')
    title = models.CharField(max_length=255, verbose_name='Título')
    description = models.TextField(max_length=1000, verbose_name='Descrição do video')
    start_date = models.DateField(verbose_name='Estará disponível quando')
    position = models.CharField(max_length=255 ,verbose_name='Qual posição')

    def __str__(self):
        return f'{self.title} {self.description} {self.start_date} - {self.url}'

video-list.html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        {% for video in videos %}
        <div>
            <h1>
                {{video.title}}
            </h1>
            <iframe width="560" height="315" src="{{video.url}}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
            <p>
                {{video.description}}
            </p>
        </div>
        {% endfor %}
    </div>
</body>
</html>

py views.:

from django.shortcuts import render, redirect
from datetime import date
from .models import *
from .forms import *
import requests
import random

def videos_list(request):
    
    if 'lead_id' in request.session:        
        videos = Video.objects.all()
        for video in videos:
            print(video.titlle)
        return render(request, 'videos-list.html', {'videos': videos})

    return redirect('registrations:create_lead')

1 answer

3


Just put the field ordering within the template metadata - something like:

class Video(models.Model):
    url = ...
    ...
    position = ...
    ...
    class Meta:
        ordering = ["position"]

Django makes use of the Python character that allows you to declare a class within a class to allow you to place a number of options and settings within each model. It is important to have in metne that this Meta is not used as a class - nor should it be called a metaclass, although historically, in Django, it started like this - it is simply used as a namespace (namespace) to declare options without the risk of them conflicting with fields of your model.

Django’s ORM uses the "Ordering" to organize its queries by default. (Note that your "position" field is text, which means that "11" comes in front of "2", for example).

The documentation for the ordering and other options of Meta is here:

https://docs.djangoproject.com/en/2.1/ref/models/options/#ordering

Another way is to make explicit the order_by in the query - change the line:

    videos = Video.objects.all()

For

    videos = Video.objects.order_by("position").all()

Documentation for query: https://docs.djangoproject.com/en/2.1/ref/models/querysets/

  • used videos = Video.objects.order_by("position").all() to res[forget my problem, but as you commented tested change the position of a video from 0 to 11 and it stood in front of video position 2 even, how could I solve this problem ? changing the type of the charfield field ?

  • 1

    I switched the field of: position = models.CharField(verbose_name='Qual posição') for position = models.IntegerField(verbose_name='Qual posição') and it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.