我已经创建了一个帖子列表,现在我想按发布日期对这个列表进行排序。如果我在 View 中使用 order_by(-post_publishing_date) shell 会向我显示此错误:
NameError: name 'post_publishing_date' is not defined
模型.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"
View .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)
网址.py
urlpatterns = [
path("it/blog/", ListPostGDV.as_view(), name="homeManuscriptusView"),
path("it/blog/<slug:slug>/", SinglePostGDV.as_view(), name="singlepostManuscriptusView"),
]
我做错了什么?
最佳答案
临时订购
嗯,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 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
排序。所以这意味着您不能“忘记”正确排序对象。
因此您不必在 View 中对其进行排序。您当然可以只定义一种这样的“固有”顺序,这里不清楚是否要使用一种。
关于python - 按日期订购邮寄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52128328/