'Muti-array result in models django
I have a second instance of database called slave_db this database have tables like this, the profile
and the details of lands
I created a model.py for these
from django.db import models
class Fields(models.Model):
field_id = models.IntegerField()
field_name = models.CharField(max_length=50)
class Meta:
managed = False
db_table = 'tbl_fields'
class Profile(models.Model):
profile_id = models.IntegerField()
name = models.CharField(max_length=20)
fields = models.OneToOneField(Fields)
class Meta:
managed = False
db_table = 'tbl_profile'
I also have my serialize.py
from rest_framework import serializer
from .models import Profile
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ['profile_id','control_no','name','fields']
then in my views.py
from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.generics import get_object_or_404
from .models import Profile
from .serializers import Profile Serializer
@api_view(['GET'])
def ProfileDetails(request):
control_no = request.GET.get("control_no")
details = Profiles.objects.using("slave_db").select_related("fields").filter(control_no = control_no)
detailSerializer = ProfileSerializer(details, many=True)
print(detailSerializer)
now the result is
[
{
"profile_id": 1,
"control_no": "8-001",
"name": "Foo",
"fields": "8-001"
},
{
"profile_id": 1,
"control_no": "8-002",
"name": "Bar",
"fields": "8-002"
},
]
how can i get the data properly and have a result like this?.
[
{
"profile_id": 1,
"control_no": "8-001",
"name": "Foo",
"fields": [
{
"field_id": 1
"field_name": "Charlie Land"
},
{
"field_id": 2
"field_name": "Alpha Land"
}
]
},
{
"profile_id": 1,
"control_no": "8-002",
"name": "Bar",
"fields": [
{
"field_id": 3
"field_name": "Genesis Land"
},
{
"field_id": 4
"field_name": "Zebra Land"
},
{
"field_id": 5
"field_name": "Master Land"
}
]
},
]
I tried models.ManyToManyFields(Field) then used the prefetch_related but upon checking the executed query it does not run the joining of the 2 tables. and there were no result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


