I am trying to show the 8 most recent scans added by doing this:
def index(request):
....
recent_scans = Image.objects.filter(category='Scan').order_by('-date_added')[:8]
...
It “works,” but it is not literally getting the 8 most recent scans. The order is different compared to the order for the def scans. The order is not completely different, it’s just that there a few scans misplaced.
What is weird is that it works in this view:
def scans(request):
image_list = Image.objects.filter(category='Scan').order_by('-date_added')
Taking out the [:8] to see if it’ll sort correctly does NOT work, though…so I don’t know what it wrong. My only guess is that the Image model is connected through a ManytoMany…
I’ve also tried this:
recent_scans = Image.objects.filter(category='Scan').latest('date_added')
But it comes with this error:
Caught TypeError while rendering: ‘Image’ object is not iterable
Here is my model, btw:
class Image(models.Model):
CATEGORY_CHOICES = (
('Cover', 'Cover'),
('Scan', 'Scan'),
('Other', 'Other'),
)
title = models.CharField(max_length=128)
image = models.ImageField(upload_to="images/")
category = models.CharField(max_length=10, choices=CATEGORY_CHOICES)
contributor = models.ManyToManyField(Contributor, blank=True, null=True)
date_added = models.DateField(auto_now_add=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
I’ve tried adding ‘get_latest_by = “date_added”` to the Meta class in my models, but that did not work either.
I do not know why it doesn’t correctly order by
date_addedeven though in myIssuemodel, it does. My only guess is that the database doesn’t correctly order by the latest item if it’s aDateFieldand not aDateTimeField. Weird, because, again, theIssuemodel does the same.So, I’ve simply just worked around it by sorting by the
idand it works great!