Francisco Ghelfi
Francisco Ghelfi

Reputation: 962

Django: foreignkey values with get() method

I need to know how can I get foreignkey field´s values instead of ID with the get method.

I´m sending a queryset from view to template as a JsonResponse. An specific instance info, so I use the get() method

def TareaDetailView(request):
    ID = request.POST.get('id')
    tareas_todas = Tareas.objects.values()
    tarea = tareas_todas.filter(pk=ID).get()

    return JsonResponse({'tarea': tarea})

I get the info at the browser but with the field names change from "empresa" to "empresa_id", for example.

This is my model with the original field names.

class Tareas(models.Model):
    creador = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
    destinatario = models.ForeignKey(User,  related_name='destinatario',  blank=True, null=True, on_delete=models.CASCADE)
    titulo = models.CharField(max_length=100, blank=True, null=True)
    tarea = models.TextField(max_length=500, blank=True, null=True)
    resuelto = models.BooleanField(default=True)
    fecha_creacion = models.DateField(default=datetime.date.today, blank=True, null=True)
    fecha_limite = models.DateField(default=datetime.date.today, blank=True, null=True)
    fecha_resuelto = models.DateField(default=datetime.date.today, blank=True, null=True)
    empresa = models.ForeignKey("Contactos", blank=True, null=True,                                        on_delete=models.CASCADE)
    persona_empresa = models.ForeignKey("Personas", blank=True, null=True,                                     on_delete=models.CASCADE)

And this is what I can check at the browser console.

tarea:
    creador_id: 1
    destinatario_id: 1
    empresa_id: 6
    fecha_creacion: "2019-03-10"
    fecha_limite: "2019-03-15"
    fecha_resuelto: "2019-03-10"
    id: 210
    persona_empresa_id: 3691
    resuelto: false
    tarea: "Habrá que hacer alguna cosa maravillosa."
    titulo: "Esta es una tarea de prueba"

An this is teh Ajax I use to get the data and show it in the template.

<script>
   $(function(){
        $('.show_tarea').on('click', function (e) {
            e.preventDefault();
            let tarea_id = $(this).attr('id');

            $.ajax({
                url:'/catalog/tareas-detail/',
                type:'POST',
                data: $('#form_tarea_'+tarea_id).serialize(),
                success:function(response){
                    console.log(response);
                    $('.show_tarea').trigger("reset");
                    openModal(response);
                },
                error:function(){
                    console.log('something went wrong here');
                },
            });
        });
    });

    function openModal(tarea_data){
        $('#creador').text(tarea_data.tarea.creador_id);
        $('#destinatario').text(tarea_data.tarea.destinatario_id);
        $('#titulo').text(tarea_data.tarea.titulo);
        $('#tarea').text(tarea_data.tarea.tarea);
        $('#resuelto').text(tarea_data.tarea.resuelto);
        $('#fecha_creacion').text(tarea_data.tarea.fecha_creacion);
        $('#fecha_limite').text(tarea_data.tarea.fecha_limite);
        $('#fecha_resuelto').text(tarea_data.tarea.fecha_resuelto);
        $('#empresa').text(tarea_data.tarea.empresa_id);
        $('#persona_empresa').text(tarea_data.tarea.persona_empresa_id);
        $('#modal_tareas').modal('show');
    };
</script>

First: I want to know how can I get the foreignkey values not the ids. Second: Why are the filed names changing? It´s something the jsonresponse does?

Thanks!

Upvotes: 0

Views: 200

Answers (3)

NVS
NVS

Reputation: 401

You have to store the data in some dict or json from foreignkey. Like

my_json = {
    "creador_name": tarea.creador.name,
    "creador_mobile_number": tarea.creador.mobile_number,
    "destinatario" :tarea.destinatario.something,
    "titulo": tarea.titulo,
    "tarea": tarea.tarea,
    "resuelto":tarea.resuelto,
    ......
    so on
    } 

now pass it you return JsonResponse({'tarea': my_json})

Upvotes: 1

WeGi
WeGi

Reputation: 1926

You only get the IDs, because inside the database only the id of the Foreign Element ist saved.

If you want to transfer the values via AJAX, you have to retrieve and add them to your result. For Example:

def TareaDetailView(request):
ID = request.POST.get('id')
tareas_todas = Tareas.objects.values()
tarea = tareas_todas.filter(pk=ID).get()

empresa = Contactos.objects.get(id=tarea.empresa.id) 

return JsonResponse({'tarea': tarea,
                     'empresa': empresa})

This is a really cumbersome way. Django REST Framework would be suitable if all your functions return JSON and you do not use Djangos frontend.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599580

The field names aren't changing, that's what they actually are.

Really you're trying to use values for something it's not intended to do. If you want to serialize a model instance together with its related items, you should look at Django REST Framework's serializers, which can do this and more.

Upvotes: 0

Related Questions