我已经创建了一个帖子列表,现在我想按发布日期订购此列表。如果我在视图中使用 order_by(-post_publishing_date)外壳程序向我显示此错误:
NameError:名称'post_publishing_date'未定义
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"),
]
我做错了什么?
答案 0 :(得分:3)
Python是正确的。没有 identifier post_publishing_date
,您通过字符串传递列的名称,因此:
class ListPostGDV(ListView):
model = PostModel
template_name = "manuscriptus_home.html"
queryset = PostModel.objects.filter().order_by('-post_publishing_date')
请注意,您还可以在Meta
类中为模型赋予“固有”顺序:
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:
ordering = ['-post_publishing_date']
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
如果您执行此操作,则对-post_publishing_date
隐式排序对该模型的所有查询。因此,这意味着您不能“忘记”正确订购对象。
因此,您不必在视图中订购。当然,您只能定义一种这样的“固有”顺序,不清楚是否要在这里使用。
答案 1 :(得分:1)
order_by参数应为字符串:
queryset = PostModel.objects.filter().order_by('-post_publishing_date')