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

183
Visualizações
Concatenate foreign key fields with delimiter Django

Lets say I have 2 models with a foreign key relation which are used to bundle books:

class Bundle(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=20)
    isbn = models.CharField(max_length=13)
    bundle = models.ForeignKey(Bundle)

we'll identify the bundles by concatenating the ISBN numbers with the delimiter like so:

123456788 & 123456789

To further export a list of available bundles for further processing we need that number.

I'm aware I could use:

for bundle in Bundle.objects.all():
    complex_isbn = ' & '.join(bundle.book_set.all().values_list('isbn', flat=True))

But this would just be too slow for the real-world purpose. Is there a way I could use annotate to accomplish this? If so, how? I'm struggling to find my way through the docs on how to accomplish concatenating multiple foreign key entries.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can make use of the StringAgg aggregate function [Django-doc], which is only available for PostgreSQL. You thus can annotate the Bundles with the complex ISBN:

from django.contrib.postgres.aggregates import StringAgg

Bundle.objects.annotate(
    complex_isbn=StringAgg('isbn', delimiter=' & ')
)

The Bundles that arise from this queryset will have an extra attribute .complex_isbn.

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