Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

538
Vistas
Django, how to rename images using a new auto-numbering per foreign key?

Ok, that title is probably as vague as vague things can get, but I couldn't come up with something good. Let me explain my problem.

For the explanation, I'll use books as an example, just because that's easy. So, imagine I have 2 models like this:

class Book(models.Model):
    title = models.CharField(max_length=100)


class BookImage(models.Model):
    book = models.ForeignKey(Book)
    image = models.ImageField()
    is_cover = models.BooleanField()

Now, as you can see a book can have multiple images. I want to rename the uploaded images to [book title]-[image-id].jpg (or whatever image extension there is of course). However, I want image-id to be unique per book. If that makes sense.

So if I have BookA, I want the images to be called BookA-1, BookA-2 and BookA-3 etc. And BookB starts at 1 again, BookB-1, BookB-2, BookB3 etc.

Any idea how I can do this? I've been thinking about it myself, but I can't come up with a really good solution. At first I thought I could do a count on the number of images and add 1 to that, but then you would run into problems if you delete images. I also thought about just keeping track of the ids in a separate Model, but that sounds so overly 'complicated'. And to make things 'worse', I would like to upload multiple images at once (well, the image upload is an inline in the Django admin), so it has to be able to work with that too... So, I was wondering if anyone here has a good idea? Is there even a simple solution?

I've also been googling a bit, but either nobody ever had any problems with this, or I just (well, probably) can't come up with the correct search term (in the same way I couldn't come up with a correct title :P).

Thanks for reading!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

firs you define a function to handle the upload image and pass this to your imagefield.

def book_image_upload(instance, filename):
        book_title = instance.book.title
        instance_id = instance.id
        extension = filename.split(".")[-1]
        new_filename = "%s-%s.%s" %(book_title, instance_id,extension)
        new_filepath = "books/%s" %(new_filename)
        return new_filepath

class BookImage(models.Model):
    book = models.ForeignKey(Book)
    image = models.ImageField(upload_to=book_image_upload)
    is_cover = models.BooleanField()
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda