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

550
Visualizações
How to annotate JSON fields in Django?

I have a model like this:

class MyModel(models.Model):
    details = models.JSONField()
    # other fields

I want to annotate some fields from this model like this:

qs = MyModel.objects.filter(id__in=given_list).annotate(
         first_name=F('details__first_name'),
         last_name=F('details__last_name')
     )

However the F() expression is not considering the json keys, its just returning the details field only.

I am using MySQL, so cannot use KeyTextTransform.

I tried using RawSQL like this:

qs = MyModel.objects.filter(id__in=given_list).annotate(
         first_name=RawSQL("(details->%s)", ('first_name',)),
         last_name=RawSQL("(details->%s)", ('last_name',))
     )

But it was giving this error:

MySQLdb._exceptions.OperationalError: (3143, 'Invalid JSON path expression. The error is around character position 1.')

So what can I do to make everything work as expected?

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

0

You can use JSONExtract, it will be easier to write and understand:

from django_mysql.models.functions import JSONExtract
qs = MyModel.objects.filter(id__in=given_list).annotate(
         first_name=JSONExtract('details', '$.first_name'),
         last_name=JSONExtract('details', '$.last_name')
     )
over 4 years ago · Santiago Trujillo Relatório

0

MySQL json extractions have a special syntax using jsonfield->"$.key". Try with this:

qs = MyModel.objects.filter(id__in=given_list).annotate(
    first_name=RawSQL("(details->%s)", ('$.first_name',)),
    last_name=RawSQL("(details->%s)", ('$.last_name',))
)
over 4 years ago · Santiago Trujillo Relatório

0

You can just add properties to your MyModel and have them return the corresponding information

class MyModel(models.Model):
    details = models.JSONField()
    
    @property
    def first_name(self):
        return self.details['first_name']
    @property    
    def last_name(self):
        return self.details['last_name']
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