Field appears as undefined

In the view where I show the records, among other fields I want to show one that is “estado_cod_id”
I assign this field at the time of registering and assign it 1
The state field is related to another table where the different states are found.
The problem is that when displaying the records, the estado_cod_id field appears as undefined but looking at the database I see that it was added correctly and is related to the estado_cod_id table.
I show parts of code so you can see how I do it.

class RegistrarReclamacion(CreateView):
    model = Rec
    form_class = RecForm
    template_name = 'reclamaciones/crear_reclamacion.html'

    def post(self, request, *args, **kwargs):
        request.headers.get('x-requested-with') == 'XMLHttpRequest'
        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            form = self.form_class(request.POST)

            if form.is_valid():
                nueva_reclamacion = Rec(
                    fecha_reclamacion = form.cleaned_data.get('fecha_reclamacion'),
                    num_reclamacion = form.cleaned_data.get('num_reclamacion'),
                    num_cliente = form.cleaned_data.get('num_cliente'),
                    empresa = form.cleaned_data.get('empresa'),
                    tipo = form.cleaned_data.get('tipo'),
                    motivo = form.cleaned_data.get('motivo'),
                    descripcion = form.cleaned_data.get('descripcion'),
                    solucion = form.cleaned_data.get('solucion'),
                    otros_solucion = form.cleaned_data.get('otros_solucion'),
                    aprueba = form.cleaned_data.get('aprueba'),
                    del_dep_code = form.cleaned_data.get('del_dep_code'),
                nueva_reclamacion =
                nueva_reclamacion.estado_cod_id = "1"
                mensaje = f'{self.model.__name__} registrada reclamacion correctamente!'
                error = 'No hay error'
                response = JsonResponse({'mensaje':mensaje,'error':error})
                response.status_code = 201
                return response
                mensaje = f'{self.model.__name__} no se ha podido registrar!'
                error = form.errors
                response = JsonResponse({'mensaje':mensaje,'error':error})
                response.status_code = 400
                return response
            return redirect('inicio_reclamaciones')

class Sat_estados(models.Model):
    codigo = models.IntegerField(verbose_name='codigo')
    nombre = models.CharField(max_length=50, verbose_name='Nombre')
    descripcion = models.CharField(max_length=100, verbose_name='Descripcion')

class Rec(models.Model):
    id = models.AutoField(primary_key=True)
    estado = models.IntegerField(verbose_name='estado', null=True)
    fecha_reclamacion = models.DateField(null=True,)
    fecha_resolucion = models.DateField(verbose_name='Fecha_resolucion', null=True)
    num_reclamacion = models.CharField(max_length=100, null=True)
    num_cliente = models.CharField(max_length=100, null=True)
    empresa = models.CharField(max_length=100, null=True)
    tipo = models.CharField(max_length=100,null=False,blank=False,choices=TIPO_EMPRESA,default='')
    atiende = models.CharField(max_length=100, null=True,)
    atiende_code = models.IntegerField(verbose_name='Atiende_code', null=True)
    departamento = models.CharField(max_length=100, null=True)
    del_dep_code = models.CharField(max_length=100, null=True)
    via = models.CharField(max_length=100,null=False,blank=False,choices=VIA,default='')
    motivo = models.CharField(max_length=100,null=False,blank=False,choices=MOTIVO_RECLAMACION,default='')
    otros_motivo = models.CharField(max_length=100, verbose_name='Otros Motivos', null=True)
    descripcion = models.TextField(max_length=100, verbose_name='Descripcion', null=True)
    solucion = models.CharField(max_length=100,null=False,blank=False,choices=RESOLUCION,default='')
    otros_solucion = models.CharField(max_length=100, verbose_name='Otros Solucion', null=True)
    aprueba = models.CharField(max_length=100, verbose_name='Aprueba', null=True)
    aprueba_codigo = models.IntegerField(verbose_name='Aaprueba_codigo', null=True)
    aprueba_selected = models.CharField(max_length=100, verbose_name='Aprueba_selected', null=True)
    imagen = models.ImageField(upload_to='imagenes/', verbose_name='Imagen', null=True)
    estado_cod = models.ForeignKey(Sat_estados, null=True,blank=True,on_delete=models.CASCADE)

The estad_cod field is a reference to the primary key of Sat_estados.

Do you have an entry in the Sat_estados table with an id = 1?

Yes, I have like four records, id=1, id=2…

So what code do you have that is saying:

I did not explain myself well, in the registration list I want the name associated with the relationship of estado_cod to appear
That is, estado_cod = 1 which corresponds to id=1,name=Draft of the table sat_estados
This sat estados name field is what I want to display.

In general, you have an instance of Sat_estados called un_estado, then you refer to the nombre field as un_estado.nombre.

In this particular case, let’s say you have an instance of Rec called un_rec.

The field, un_rec.estado_cod then is a reference to an instance of Sat_estados.

Combining these two means that you get the nombre field as un_rec.estado_cod.nombre

I can’t get it to show the field. I am attaching part of the js code for the DataTable, which is where I call each field from. The last one would be the status field (rec.estado_cod.nombre)

function listadoReclamaciones(){
        url: "/reclamaciones/listado_reclamaciones/",
        dataType: "json",
        success: function(response){
            $('#tabla_reclamaciones tbody').html("");
            for(let i = 0;i < response.length;i++){
                let fila = '<tr>';
                fila += '<td>' + (i +1) + '</td>';
                fila += '<td>' + response[i]["fields"]['num_reclamacion'] + '</td>';
                fila += '<td>' + response[i]["fields"]['motivo'] + '</td>';
                fila += '<td>' + response[i]["fields"]['fecha_reclamacion'] + '</td>';
                fila += '<td>' + response[i]["fields"]['aprueba'] + '</td>';
                fila += '<td>' + response[i]["fields"]['del_dep_code'] + '</td>';
                fila += '<td>' + response[i]["fields"]['rec.estado_cod.nombre'] + '</td>';

That’s because these objects only exist in the server. You need to ensure this data is in the response being returned.

Please show the view where you’re building this response.

In the browser console it can be seen as if it fetched the field and it has a value.


Please see my previous response.

class ListadoReclamacion(ListView):
    model = Rec

    def get_queryset(self):
        return self.model.objects.filter(estado_cod_id=1)

    def get(self,request,*args,**kwargs):
        request.headers.get('x-requested-with') == 'XMLHttpRequest'
        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return HttpResponse(serialize('json',self.get_queryset()),'application/json')
            return redirect('inicio_reclamaciones')

The easiest way to handle this would be to annotate that value as a new field in your get_queryset function, and then reference that new field by name within the JavaScript.

Sorry, I don’t understand when you say this.

Start here: Aggregation | Django documentation | Django
Make sure you read and understand the examples as well as the text.

Note: As you’re reading this, be aware of the differences between aggregate and
annotate. A lot of the functionality is the same, but there are some differences. For what you’re looking to do here, you want to pay more attention to annotate.

Then I’d recommend you play with some queries in the Django shell to get some experience working with annotate.