Django REST Framework: Single list of results obtained in Serializer

Asked 2 years ago, Updated 2 years ago, 95 views

The Django REST Framework is creating an API to retrieve data from the master.
models.py

class CommonMaster(models.Model):
    type=models.CharField(max_length=20)
    type_id=models.IntegerField()
    key_name=models.CharField(max_length=20)
    value=models.CharField (max_length=1024, null=True)

records:

{"id":"1", "type":"cat", "type_id":"1", "key_name":"Breed", "value":"Somali"}
{"id":"2", "type":"cat", "type_id":"1", "key_name":"Country", "value":"Canada"}
{"id":"3", "type":"cat", "type_id":"2", "key_name":"Breed", "value":"Bengal"}
{"id":"4", "type":"cat", "type_id":"2", "key_name":"Country", "value":"America"}
{"id":"5", "type":"dog", "type_id":"1", "key_name":"Breed", "value":"Shiba"}
{"id":"6", "type":"dog", "type_id":"1", "key_name":"Country", "value":"Japan"}

views.py

class CommonMasterViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = ListSerializer

    def get_queryset(self):
        returnCommonMaster.objects.all()\
                           .filter(type=self.request.query_params['type'])\
                           .filter(key_name=self.request.query_params['type_id'])

serializer.py

class ListSerializer (serializers.Serializer):
    def to_representation(self, obj):
        US>return{
            obj.key_name —Obj.value
        }

Currently, the acquisition results are

[
    {
        "Breed": "Bengal"
    },
    {
        "Country": "America"
    }
]

I would like to return JSON in the following format.

[
    {
        "Breed": "Bengal",
        "Country": "America"
    },
]

Is it possible to do so only by modifying the serializer?
Could you please let me know if there is a solution?Thank you for your cooperation.

python django

2022-09-29 22:22

1 Answers

Fixing Serializer makes it difficult, but writing it straight with Flask makes it easy.

 from flash import Flask
app = Flask(__name__)
from sqlalchemy import create_engine
engine = create_engine('connection string')

@app.route('/queryset')
defqueryset():
    result=engine.execute('SELECT type, key_name FROM table_name')
    s='[{'+','.join(map(lambdax:f'"{x.type}":"{x.key_name}"', result))+'}]'
    return Response(s, mimetype='application/json')

Also, if the keys are not duplicated, you can use a dictionary, which is easier.

import json
from flash import Flash
app = Flask(__name__)
from sqlalchemy import create_engine
engine = create_engine('connection string')

@app.route('/queryset')
defqueryset():
    result=engine.execute('SELECT type, key_name FROM table_name')
    return Response('['+json.dumps(dict(list(result))))))+'], mimetype='application/json')

I don't think Dgjango should be difficult to write in the same way (I've never used Dgjango before, so I'm not sure, but I think it's better to create a string directly from CommonMaster in Views).


2022-09-29 22:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.