oyilmaztekin oyilmaztekin - 24 days ago 7
JSON Question

Flask - POST request returns only one item

I've User and Alarm table in my database. The Alarm table related with the User.

The app handling to all authentications with the API views.

Problem

When POST request succeed the controller doesn't return all items in the database. It returns only one.

I will write here the controller codes these takes control of actions after the login succeed

I tried this

login_user(user)

for item in user.alarm:
return jsonify({
"id": item.id,
"dovizAdi": item.dovizAdi,
"mevcutDeger": item.mevcutDeger,
"beklenenDeger": item.beklenenDeger,
"oranTuru": item.oranTuru,
"tarih": item.tarih
})


returns only one item

{
"beklenenDeger": "1.56",
"dovizAdi": "ons",
"id": 1,
"mevcutDeger": "1.54",
"oranTuru": "buying",
"tarih": null
}


I tried this

result = jsonify(str(user.alarm.all()))
return result


returns all item but I can't get their values.

"[<Alarm u'ons'>, <Alarm u'ceyrek-altin'>]"


I've learned json implementation my previous project mongodb. I think I don't unserstand how json works with sql or missed some important thing in the theory. For loop statement that first example I did shouldn't be return the right results?

Answer

Your problem that you are returning in for loop instead of collecting data

result = []
for item in user.alarm:
    result.append({
        "id": item.id,
        "dovizAdi": item.dovizAdi,
        "mevcutDeger": item.mevcutDeger,
        "beklenenDeger": item.beklenenDeger,
        "oranTuru": item.oranTuru,
        "tarih": item.tarih
    })
return jsonify(result)