0

I am using mongoDB as my database, i am working on django projects and using mongoengine to connect with database. My question is if my default database in settings.py is DB1 and i want to delete all records of a collection which exists inside DB2 then how can i do this.

settings.py

import mongoengine

mongoengine.connect(
    db= "DB1",
    host='localhost',
)

models.py

class Resources(Document):
    field1= fields.StringField(max_length=20)
    field2 = fields.StringField(max_length=70)
    field3 = fields.StringField(max_length=70)
    field4 = fields.DictField()

    meta = {'collection': 'resources', 'allow_inheritance': False, '_target_db': 'DB2'}

python shell

from .models import Resources
import mongoengine
mongoengine.connect('DB2', alias='ces')
ob = Resources()
ob.switch_db('ces')
ob.field1 = value
ob.field2 = value
ob.field3 = value
ob.save()

Now i have collection resources in DB2 and it has some records, i have tried Resources.objects.all().delete() but it is not deleting records form DB2 instead it deletes records from DB1 which is default database.

Vikas Gautam
  • 239
  • 1
  • 4
  • 21
  • Have you defined DB2 in settings.py file? This is happing because you have only DB1 defined in settings.py file, and all your actions to `Resources` will take place to DB1. – Reema Parakh Feb 07 '19 at 07:23
  • no i haven't, how to define `DB2` in `settings.py`? – Vikas Gautam Feb 07 '19 at 07:51
  • Django natively dosen't support mongoDB, so you cant use the builtin django ORM. Are you using some third party library for the django mongodb integration? – Kristiyan Gospodinov Feb 07 '19 at 07:54
  • In your case I guess you have model with the same name(Resources) in your Django models and when you Resources.objects.all().delete() you are actually calling the django model and not the mongoengine document. Can you show us the code where you are calling the delete() method? – Kristiyan Gospodinov Feb 07 '19 at 08:05
  • yes i am using `djongo` to connect django with mongodb. – Vikas Gautam Feb 07 '19 at 09:41
  • my `models.py` does not have model with same name `Resources`, i think to save data we have to use `switch_db` but to remove we are not using anything like `switch_db` to tell from which DB we want to delete collection. – Vikas Gautam Feb 07 '19 at 09:44

1 Answers1

0

If each of your model is bound to 1 (and only 1) database, you can achieve what you want using connection alias and meta = {'db_alias': 'your_connectio_alias'} (docs)

See this post for an example

bagerard
  • 5,681
  • 3
  • 24
  • 48