如何在Django中按字母排序

k5hmc34c  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(118)

在我的网站上,有不同的列表排列为(a-e),(e-j),(j-o),(o-t)和所有。当用户点击这些列表中的任何一个时,我希望网站从数据库中检索数据,从所选字母范围内的标题开始。但是,我不太熟悉如何实现此功能。有人能帮我吗?
index.html

<div class="widget-content">
    <h4>Sort by letter</h4>
        <ul class="widget-links">
            {% for letter_range in letter_ranges %}
                {% if selected_range == letter_range %}
                    <li><strong>{{ letter_range }}</strong></li>
                {% else %}
                    <li><a href="?range={{ letter_range }}">{{letter_range}}</a></li>
                {% endif %}
            {% endfor %}
        </ul>

字符串
views.py

def index(request):
    letter_ranges = ['All', 'a-e', 'e-j', 'j-o', 'o-t', 't-z']
    selected_range = request.GET.get('range', 'All')

    if selected_range == 'All':
        queryset = tabir.objects.filter(is_active=True)
    else:
        start_letter, end_letter = selected_range.split('-')
        queryset = tabir.objects.filter(title__istartswith__range=(start_letter, end_letter), is_active=True)

    context = {
        "tabirs": queryset,
        "current_date": datetime.now(),
        "selected_range": selected_range,
        "letter_ranges": letter_ranges,
    }
    return render(request, "ruya/index.html", context)


models.py

class tabir(models.Model):
    id = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=200)
    description = RichTextField()
    is_active = models.BooleanField(default=False)
    is_home = models.BooleanField(default=False)
    release_date = models.DateTimeField(null=False,blank=True) #default=datetime.date.today
    create_date = models.DateTimeField(editable = False, auto_now_add=True)#default=datetime.date.today
    slug = models.SlugField(null= False, blank=True,unique=True, db_index=True, editable=False)

frebpwbc

frebpwbc1#

您可以在**Lower**[Django-doc]的字段上使用__range

from django.db.models.functions import Lower

letters = selected_range.split('-')
queryset = tabir.objects.alias(title_lower=Lower('title')).filter(
    title_lower__range=letters, is_active=True
)

字符串

相关问题