Home > OS >  How to display recent posts in django
How to display recent posts in django

Time:11-07

Here is the case, I need the last records of the model to be displayed on the page, for this I added a new pub_date record in the models to add to the queue of records, I also added this to views.py, and it kind of displays, but both records.

views.py code

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 code

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

this is what displaysenter image description here

CodePudding user response:

You are just sorting the data using order_by and assign the sorted data to a variable:

avaibilitys = Avaibility.objects.order_by('-pub_date')

If you want to get only one of them, you can do this:

avaibilitys = Avaibility.objects.order_by('-pub_date').first()

EDIT

If you want the last one, do this:

avaibilitys = Avaibility.objects.order_by('-pub_date').last()
  • Related