skip to Main Content

I just want to get the clientType.name through an ID of foreign key from Clients table and pass it to jsonResponse , I have tried but it doesn’t work below

I tried select_related but it doesn’t work
it says AttributeError: 'str' object has no attribute '_meta'

def patientdetails(request):

    patient_id = request.POST.get('patient')
    context = {
       'company' : Clients.objects.filter(id=patient_id).select_related()

    }
    qs_json = serializers.serialize('json', context)
    return JsonResponse({'data': qs_json})

models.py

class ClientType(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 = 'client_type'


class Clients(models.Model):
     client_type = models.ForeignKey(ClientType, 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)
     birthdate = models.DateField(blank=True, null=True)
     sex = models.CharField(max_length=128, blank=True, null=True)
     address = models.CharField(max_length=128, blank=True, null=True)
     occupation = models.CharField(max_length=128, blank=True, null=True)

     class Meta:
         managed = True
         db_table = 'clients'

Result data in javascript

}).done(function(data){
      var resultdata = JSON.parse(data.data);

});

2

Answers


  1. select_related: you need to pass a str.

    Clients.objects.filter(id=patient_id).select_related("clientType__name")
    
    Login or Signup to reply.
  2. If you are using from django.core import serializers

    You can try to add nested fields you need in fields parameter

    def patientdetails(request):
        patient_id = request.POST.get('patient')
        clients = Clients.objects.filter(id=patient_id)
        qs_json = serializers.serialize('json', clients, fields=['your_fields'..., 'client_type__name'])
        return JsonResponse({'data': qs_json})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search