Search code examples
djangomodelmany-to-manyrelational-databaserelationship

Django - How to reach relational field


I have Patient model which has many to many relation with ICF model. ICF model has many to one field to Unite model. In Unite model I have Unite names. I want to reach Unite names that are assigned to Patient with relations. I try to reach Unite names for each Patient. If it is more than one I cannot list them for that person. Here are my codes.

This is my patient model.

class Patient (models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255, default="doe")
    data = models.JSONField()
    Intensivecare_form = models.ManyToManyField(Intensivecare_Form)
    isDeleted = models.BooleanField(default=False)

This is my ICF model.

class Intensivecare_Form (models.Model):
    id = models.AutoField(primary_key=True)
    hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE)
    formname = models.CharField(max_length=128)
    data = models.JSONField()
    unites_id = models.ForeignKey(Unite, on_delete=models.CASCADE)

At last, This is my Unite model

class Unite (models.Model):
    id = models.AutoField(primary_key=True)
    unitename = models.CharField(max_length=128)

In my views.py file I have a function as below

def listPatients(request):
    Patients = Patient.objects.all()
    output = []
    for patient in Patients:
        unitename = []
        icfinfo = serializers.serialize('json', patient.Intensivecare_form.all())
        jsonicfinfo = json.loads(icfinfo)
        unitename.append(jsonicfinfo)
        output.append({'id': patient.id,
                       'fname': patient.name,
                       'lname': patient.lastname,
                       'data': patient.data,
                       'unitename': unitename,
                       })
    return JsonResponse(output, safe=False)

This is what output looks like. I need to reach formname in unitename

0-> id, fname..., unitename-> 0 -> fields -> unitename

enter image description here


Solution

  • It seems your ICForm is only pointing at one Unite object.

    Maybe try this to get all ICForm's in the query.

    Instead of

    unitename = []
    icfinfo = serializers.serialize('json', patient.Intensivecare_form.all())
    jsonicfinfo = json.loads(icfinfo)
    unitename.append(jsonicfinfo)
    

    Try renaming Intensivecare_form model rename unites_id to unites -- django knows to link on the id automatically and calling it unites_id could cause naming conflicts

    Intensivecare_Form(models.Model):
        unites = models.ForeignKey(Unites, on_delete=models.CASCADE)
    

    And to get all unites names just get it in one query

       unite_names = list(patient.Intensivecare_form.all().values_list('unites__unitename', flat=True))
    

    That should do it for you! Best of luck!