gpt4 book ai didi

django 模板首先显示最新数据

转载 作者:行者123 更新时间:2023-12-01 12:06:18 25 4
gpt4 key购买 nike

我必须先在上面显示数据的最新日期,在我的原始代码中,它只在上面显示最旧的数据日期,在下面列出较新的数据

django 2.2

modle.py

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse


class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])

我认为我必须在 views.py 中制作

model = Article --> order_by('-date')

类似的东西?我该怎么办?

views.py

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy

from .models import Article


class ArticleListView(LoginRequiredMixin, ListView):
model = Article
template_name = 'article_list.html'
login_url = 'login'

在下面的表格中,它会在上面列出最旧的数据,在下面列出较新的数据,我想做的是在上面列出最新的数据,在下面列出较旧的数据

article_list.html

{% extends 'base.html' %}

{% block title %}Articles{% endblock title %}

{% block content %}
{% for article in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ article.title }}</span> &middot;
<span class="text-muted">by {{ article.author }} | {{ article.date }}</span>
</div>
<div class="card-body">
{{ article.body }}
</div>
<div class="card-footer text-center text-muted">
<a href="{% url 'article_edit' article.pk %}">Edit</a> |
<a href="{% url 'article_delete' article.pk %}">Delete</a>
</div>
</div>
<br />
{% endfor %}
{% endblock content %}

感谢您的评价

最佳答案

您可以通过在模型的 Meta 中设置 ordering 来做到这一点:

要以相反的顺序显示,请在字段名称前加上减号 -

class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])

class Meta:
ordering = ['-date']

关于django 模板首先显示最新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com