Home > Net >  how to serialize data with python after getting it from firebase in django?
how to serialize data with python after getting it from firebase in django?

Time:03-25

i'm working with Django and i want to retrieve data from firebase and make it readable and serializable

when retrieving data from the default database (sqlite) i use this function :

@api_view([('GET')])
    def getPatients(request):
      patients = Patient.objects.all()
      serializer = PatientSerializer(patients , many = True)
      return Response(serializer.data)

i want to change this function to get and serialize the data from firebase .

i tried to get data from firebase and send it in the response but it is not showing in the web view page .

the solution i tried :

 @api_view([('GET')])
 def getPatients(request):
     patients = database.child('patients').get().val()
     serializer = PatientSerializer(patients , many = True)
     return Response(serializer.data)

CodePudding user response:

It sounds like you are trying to get data from Firestore.

If that is the case you need to initialize firestore and convert the data into a python dictionary using the to_dict() method.

secret = os.getenv("FIREBASE_ADMIN_SDK")
cred = credentials.Certificate(json.loads(secret))
firebase_app = initialize_app(cred)
db = firestore.client()
doc_ref = db.collection('<your_collection').doc('<your_document>')
patients = doc_ref.get().to_dict()

CodePudding user response:

this solution worked for me :

@api_view([('GET')])
def getPatients(request):
  # patients = Patient.objects.all()
  # serializer = PatientSerializer(patients , many = True)
  patients = [] # make empty list for patients
  patientsData = database.child('patients').get().val() #get all the value from firebase database
  for patient in patientsData : # fill the patients list 
    print(database.child('patients').child(patient).get().val())
    patients.append(database.child('patients').child(patient).get().val())
    print(patients)
  return Response(patients) # send it to the api
  • Related