按日期订购 post

Order post by date

我已经创建了一个 post 的列表,现在我想按发布日期对这个列表进行排序。如果我在视图中使用 order_by(-post_publishing_date),shell 会显示此错误:

NameError: name 'post_publishing_date' is not defined

models.py

class PostModel(models.Model):
    post_title = models.CharField(max_length=70)
    post_short_description = models.TextField(max_length=200)
    post_contents = models.TextField()
    post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE, related_name="connected_author")
    post_keyconcept = models.ManyToManyField(KeyConceptModel, related_name="connected_keyconcept")
    slug = models.SlugField(verbose_name="Slug", unique="True")
    post_highlighted = models.BooleanField(default=False)

    def __str__(self):
        return self.post_title

    def get_absolute_url(self): 
        return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug})

    class Meta:
        verbose_name = "Articolo"
        verbose_name_plural = "Articoli"  

views.py

class SinglePostGDV(DetailView):
    model = PostModel
    template_name = "manuscriptus_post_detail.html"


class ListPostGDV(ListView):
    model = PostModel
    template_name = "manuscriptus_home.html"
    queryset = PostModel.objects.filter().order_by(-post_publishing_date)

urls.py

urlpatterns = [
    path("it/blog/", ListPostGDV.as_view(), name="homeManuscriptusView"),
    path("it/blog/<slug:slug>/", SinglePostGDV.as_view(), name="singlepostManuscriptusView"), 
]

我做错了什么?

order_by 参数应为字符串:

queryset = PostModel.objects.filter().order_by('-post_publishing_date')

临时订购

嗯Python是正确的。没有标识符 post_publishing_date,你通过字符串传递列名,所以:

class ListPostGDV(ListView):
    model = PostModel
    template_name = "manuscriptus_home.html"
    queryset = PostModel.objects.filter().order_by(<b>'-post_publishing_date'</b>)

定义模型的固有排序

请注意,您还可以在 Meta class:

中为模型提供 "inherent" 排序
class PostModel(models.Model):
    post_title = models.CharField(max_length=70)
    post_short_description = models.TextField(max_length=200)
    post_contents = models.TextField()
    post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE, related_name="connected_author")
    post_keyconcept = models.ManyToManyField(KeyConceptModel, related_name="connected_keyconcept")
    slug = models.SlugField(verbose_name="Slug", unique="True")
    post_highlighted = models.BooleanField(default=False)

    def __str__(self):
        return self.post_title

    def get_absolute_url(self): 
        return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug})

    class Meta:
        <b>ordering = ['-post_publishing_date']</b>
        verbose_name = "Articolo"
        verbose_name_plural = "Articoli"

如果您这样做,对该模型的所有查询都将隐式-post_publishing_date排序。所以这意味着您无法 "forget" 正确排序对象。

这样您就不必在浏览量中订购它了。你当然可以只定义一个这样的"inherent"排序,这里不清楚你是否要使用一个。