I don't think you need this in a field. Remember my_gallery.images.all()[i]
will give you the i-th image in the gallery, using OFFSET and LIMIT in the SQL command, so you can just use that to get the image for each page.
Django ORM - any way to increment a field of a model instance relative to previous instances?
-
10-07-2023 - |
Domanda
I have a problem I'm trying to tackle here related to routing and Django's ORM. So I am trying to model an image gallery. Seems simple enough, a many to one from images to gallery. This all works fine, but I need pages for each individual image, with their own urls. For example, something like /<gallery_id>/<image_number>/
, where the image number is relative to just the set of images related to the gallery. So like the first image would be /<gallery_id>/1/
and so on. Is there any way I can have an attribute, property, method or something that will give me this so i can use it in a route? My models:
class Gallery(models.Model):
class Meta:
verbose_name_plural = 'galleries'
name = models.CharField(max_length=400)
def get_absolute_url(self):
return reverse('gallery', args=[str(self.id)])
def __unicode__(self):
return self.name
class Image(models.Model):
img = models.FileField(max_length=100, upload_to='galleries')
thumb = models.FileField(max_length=100, upload_to='gallery-thumbs')
date = models.DateField(auto_now_add=True)
gallery = models.ForeignKey(Gallery, related_name='images')
class Meta:
ordering = ["-img"]
def __unicode__(self):
return self.gallery.name
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow