Not saving the record into mongodb DB in Django, Actually I am trying explore multiple different DB (Postgresql, Mongodb) in a single app
Asked Answered
S

2

6

I am trying to use multiple different DB in a single app(todo). I am using Djongo package for dealing mongodb.

Settings.py

DATABASES = {
    'default':{},
    'sql_db': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'my_db',
        'USER': '******',
        'PASSWORD': '***',
        'HOST': 'localhost',
        'PORT': '5432',
    },
    'mongodb':{
        'ENGINE': 'djongo',
        'NAME': 'mongo_db'
    }
}

todo/models.py

class Task(models.Model):
    todo = models.CharField(max_length=200)
    status = models.BooleanField(default=False)
    
    def __str__(self):
        return self.todo

todo/serializers.py

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

todo/views.py

@api_view(['POST'])
def todoCreate(request):
    serializer = TodoSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        serializer.save(using='mongodb')
    return Response(serializer.data)

it successfully saved the record into 'sql_db' but not save in the 'mongodb'.

Sorus answered 7/7, 2021 at 19:22 Comment(0)
A
0

My suggestion is to put the dual database saving into a save function in models.py:

class Task(models.Model):
...

    def save(self, *args, **kwargs):
        super(Task, self).save(using='sql_db')
        super(Task, self).save(using='mongodb')

and drop the 2nd save in the view.

This is so any save of a Task object will trigger the dual save (E.g. from the django admin or another script) rather than just when it comes from this one serializer view.

I'm not sure the serializer.save method passes the 'uses' through to the objects save function which may be the problem for you. If you want to do it in the serializer then you may have to override the create and save in the TodoSerializer: see Serializers

Ap answered 30/7, 2022 at 13:41 Comment(0)
K
-1

For dealing with module named Djongo for connecting Django with MongoDb , one should be completely aware of the modules versions being used in the environment.

asgiref==3.5.0,
Django==4.0.3,
djongo==1.3.6,
dnspython==2.2.1,
pykerberos==1.2.4, 
pymongo==3.12.1,
python-snappy==0.6.1, 
pytz==2022.1,
sqlparse==0.2.4, 

configure the Database settings in the settings.py. Its not necessary to use host while connnecting to the localhost of MongoDb.






      DATABASES = {
            'default': {
                'ENGINE': 'djongo',
                'NAME': 'your-db-name',
            
            }
    } 
Kanter answered 25/7, 2022 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.