Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

546
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda