Serialize QuerySet to JSON with FK DJANGO

Serialize QuerySet to JSON with FK DJANGO

Problem Description:

I want to send a JSON of a model of an intersection table so I only have foreign keys saved, I tried to make a list and then convert it to JSON but I only receive the ids and I need the content, I also tried in the back as a temporary solution to make a dictionary with the Queryset but the ‘<>’ makes it mark an error in the JS, does anyone know a way to have the data of my foreign keys and make them a JSON?

models:

class Periodos(models.Model):
    anyo         = models.IntegerField(default=2022)
    periodo      = models.CharField(max_length=10)
    fecha_inicio = models.DateField(blank=True, null=True)
    fecha_fin    = models.DateField(blank=True, null=True)
    class Meta:
        app_label = 'modelos'
        verbose_name = u'periodo'
        verbose_name_plural = u'Periodos'
        ordering = ('id',)
    def __str__(self):
        return u'%s - %s' % (self.anyo,self.periodo)

class Programas(models.Model):
    programa  = models.CharField(max_length=255,blank=True, null=True)
    activo    = models.BooleanField(default=True)
    class Meta:
        app_label           = 'modelos'
        verbose_name        = u'Programas'
        verbose_name_plural = u'Programas'  
    def __str__(self) -> str:
        return self.programa


class Programa_periodo(models.Model):
    periodo     = models.ForeignKey(Periodos, related_name='Programa_periodo_periodo',on_delete=models.CASCADE)
    programa    = models.ForeignKey(Programas, related_name='Programa_periodo_Programa',on_delete=models.CASCADE)
    
    class Meta:
        app_label           = 'modelos'
        verbose_name        = u'Programa Periodo'
        verbose_name_plural = u'Programa Periodo'  

    def __str__(self) -> str:
        return self.programa.programa

py where i send data

def iniciativa(request):
    if request.user.is_authenticated:
        context                    = {}
        
        context['marcas']          = json.dumps(list(Marcas.objects.values()))
        context['eo']              =  get_estructura_org()
        
        #This is where I call the data 
        programa = Programa_periodo.objects.all()
        
        #These two only return the ids
        # context['programa_periodos'] = json.dumps(list(Programa_periodo.objects.values()))
        #context['programa_periodos'] = serializers.serialize("json", Programa_periodo.objects.all())

        #One of my try but fail for the '<>'
        programa_periodo = {} 
        for pg in  programa:
            programa_periodo[pg.periodo] = pg.programa
                    
        context['programa_periodos'] = programa_periodo
        
        return render(request, 'agregar_iniciativa.html', context)
    else:
        return HttpResponseBadRequest('Favor de ingresar sesión en el sistema.', format(request.method), status=401)

Solution – 1

I am not sure that I get the question right, but if you need a special field value from foreign key you can use smth like:

Programa_periodo.objects.values("id", "periodo__periodo", "programa__programa")

With double underscore. Try it in the shell first. Check the docs here https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject