skip to Main Content

I’m confused why the values I fetch in foreign key is missing or not pops in Ajax result , all I want is to get the value name through the foreign key id using ajax, I tried many ways like select_related() but it doesn’t work.

The image below shows the result of the ajax through consolelog which contains data from supplier table and supplier_type table but only the supplier table fetch the data and missing supplier name data which foreign key name? I just tried supplier_type__name but it seems doesn’t work. Is there any problem with the implementation?

enter image description here

ajax

$('.get_supplier_details').click(function (event) {

  var patient_id = $('#selected-patient').find(":selected").val();

  $.ajax({
    type: "POST",
    url: "{% url 'supplier-details' %}",
    data:{
        supplier: supplier_id
    }
    }).done(function(data){
      console.log(data);  //

    });

});

vies.py

from main.models import (Supplier, SupplierType)

def patientdetails(request):
   supplier_id = request.POST.get('supplier')
   clients = Supplier.objects.filter(id=supplier_id ).select_related()
   qs_json = serializers.serialize('json', clients, fields=['first_name', 'middle_name', 'supplier_type__name'])

   return JsonResponse({'data': qs_json})

models,py

class SupplierType(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated_at = models.DateTimeField(blank=True, null=True, auto_now=True)
    class Meta:
        managed = True
        db_table = 'supplier_type'

class Supplier(models.Model):
    supplier_type = models.ForeignKey(SupplierType, models.DO_NOTHING)
    first_name = models.CharField(max_length=128, blank=True, null=True)
    middle_name = models.CharField(max_length=128, blank=True, null=True)
    last_name = models.CharField(max_length=128, blank=True, null=True)
    class Meta:
        managed = True
        db_table = 'supplier'

2

Answers


  1. Unfortunately, serialization of foreign key fields isn’t that simple. You’ll either need to plug in the django rest framework (well worth getting your head around), or, if that’s overkill for this situation, you could try using F to bring your ForeignKey name field to the ‘front’ of the field list via annotate. try something like:

    from django.db.models import F
    
    
    clients = (Supplier.objects
       .filter(id=supplier_id )
       .select_related('supplier_type')
       #use F to evaluate supplier_type__name and add to new field
       .annotate(supplier_type_name = F(supplier_type__name))
    )
    qs_json = serializers.serialize(
        'json', 
        clients, 
        #use our new field for serialization
        fields=['first_name', 'middle_name', 'supplier_type_name']
    )
    
    Login or Signup to reply.
  2. Get the SupplierType ID and store it in variable in your func.

    Then Supplier.objects.filter(supplier_type_contains=supplier_id).

    This is dynamic way to store it on the go from value you may get from Ajax posted for django.

    You don’t need to use prefetch_related or select_related serialization.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search