在這種情況下,我需要在頁面上顯示模型的最后一條記錄,為此我在模型中添加了一個新的 pub_date 記錄以添加到記錄佇列中,我也將其添加到了 views.py,并且它種顯示,但都記錄。
視圖.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
模型.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
這就是顯示
uj5u.com熱心網友回復:
您只是使用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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/351088.html
