Search code examples
pythondjangofirebasedjango-rest-frameworkfirebase-admin

firebase-admin adding a random alphanumeric key to the realtime database when using push()


I am using the Python firebase-admin library to integrate Django rest framework and Firebase Realtime storage. I am using the push() function to create a new child node. However, the function adds an alphanumeric key to each child. Is there a way I can avoid that and add my own custom keys to the data?

See example below:

    def post(self, request):
        """Function to handle post requests

        Args:
            request (_type_): _description_
        """

        # Get the data to be posted from the request 
        name = request.POST.get('name')
        age = request.POST.get('age')
        location = request.POST.get('location')

        # Set the reference to the database
        ref = db.reference('/')

        # Push the data to the database
        ref.push({"user1" : {
            'Name': name,
            'Age': age,
            'Location': location
        }})

        return JsonResponse({"message": "Data posted successfully"}, status=200)

When I run this, the node is created as follows

{
    "data": {
        "-NNzIPh4SUHo6FLhs060": {
            "user1": {
                "Age": "20",
                "Location": "US",
                "Name": "Dummy name 2"
            }
        },
        "user2": {
            "Age": "22",
            "Location": "count1",
            "Name": "Dummy 1"
        }
    }
}

The -NNzIPh4SUHo6FLhs060 key is created which I want to customize.


Solution

  • Calling push() is an instruction to the database to generate a new unique child node for the data that you pass. If you want to write the data directly at the path you specify, use set() instead of push().

    Also see the Firebase documentation on saving data