如何在django中显示最近的帖子
How to display recent posts in django
这里是这样的,我需要在页面上显示模型的最后一条记录,为此我在模型中添加了一条新的pub_date记录以添加到记录队列中,我也将此添加到 views.py,它有点显示,但两个记录。
views.py代码
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
def description(self):
return self.description_text
def price(self):
return self.price_text
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
numbers = Number.objects.all()
context['numbers'] = numbers
return context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
avaibilitys = Avaibility.objects.order_by('-pub_date')
context['avaibilitys'] = avaibilitys
return context
models.py代码
class Avaibility(models.Model):
name_text = models.CharField(max_length=200)
apply_text = models.CharField(max_length=200)
presence_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', null=True)
def __str__(self):
return self.name_text
def __str__(self):
return self.apply_text
def __str__(self):
return self.presence_text
这是显示的内容
您只是使用 order_by
对数据进行排序,并将排序后的数据分配给一个变量:
avaibilitys = Avaibility.objects.order_by('-pub_date')
如果你只想得到其中一个,你可以这样做:
avaibilitys = Avaibility.objects.order_by('-pub_date').first()
编辑
如果您想要最后一个,请执行以下操作:
avaibilitys = Avaibility.objects.order_by('-pub_date').last()
这里是这样的,我需要在页面上显示模型的最后一条记录,为此我在模型中添加了一条新的pub_date记录以添加到记录队列中,我也将此添加到 views.py,它有点显示,但两个记录。
views.py代码
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
def description(self):
return self.description_text
def price(self):
return self.price_text
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
numbers = Number.objects.all()
context['numbers'] = numbers
return context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
avaibilitys = Avaibility.objects.order_by('-pub_date')
context['avaibilitys'] = avaibilitys
return context
models.py代码
class Avaibility(models.Model):
name_text = models.CharField(max_length=200)
apply_text = models.CharField(max_length=200)
presence_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', null=True)
def __str__(self):
return self.name_text
def __str__(self):
return self.apply_text
def __str__(self):
return self.presence_text
这是显示的内容
您只是使用 order_by
对数据进行排序,并将排序后的数据分配给一个变量:
avaibilitys = Avaibility.objects.order_by('-pub_date')
如果你只想得到其中一个,你可以这样做:
avaibilitys = Avaibility.objects.order_by('-pub_date').first()
编辑
如果您想要最后一个,请执行以下操作:
avaibilitys = Avaibility.objects.order_by('-pub_date').last()