Home > Enterprise >  How to use different key name in MongoDB while working with Django?
How to use different key name in MongoDB while working with Django?

Time:12-20

I am working on developing a micro service using Django, where I use MongoDB as backend.

Folks who wrote the main code used java hence the data already present in the MongoDB collections follows camelcase pattern for e.g. firstName is the key name.

Now while working with python I like to name my variables and functions using snake casing like first_name and get_first_name().

What I want is that inside the code I want to refer first name as first_name everywhere but while saving/updating the first name in DB and while returning JSON response of the user data I want to return it as firstName?

Is there any way to achieve this behaviour? Please help me?

CodePudding user response:

Use db_column as argument in your models field constructor as described here: https://docs.djangoproject.com/en/4.0/ref/models/fields/#db-column

Edit: Regarding the API Output, you have two possibilities, either use a Serializer or the .values() function.

Serializer with django-restframework:

from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

serializer = CommentSerializer(comment)
serializer.data
# {'email': '[email protected]', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}

https://www.django-rest-framework.org/api-guide/serializers/

.values(): Blog.objects.values('id', 'name') where the arguments define the output key values, https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values

  • Related