Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interacting with an external django project from within another django project

I'm looking for a way to interact with the models of a django project from within a separate django project. I don't mean different apps, I mean 2 separate projects with 2 separate settings files.

I'm in the process of migrating an old web store (really old, it's all static html) to our django based backend. To do this, I created a separate django app that would handle all of the crawling and parsing, using the django orm and a few views for human assisted parsing. Now I'm at a point where I need to populate the catalog data of our backend with the data stored in the crawler project. I've spent the better part of the last 2 days trying to figure out a method, with no luck.

What I'd ideally like to do is import the store project as a module into a django command class and then interact with it that way (mind you, they are working off of 2 separate settings files, so setup_environ won't work). I'd like to avoid serializing the crawler data and then importing it from the store or interacting with the store database outside of django's orm because this project is far from over and I'd prefer to keep things as flexible as possible.

What would you suggest? I'm up for wild ideas, so long as I can interact with the orm of both projects from within a single script.

like image 582
Blake Avatar asked Oct 09 '22 14:10

Blake


1 Answers

I've done this before...

So,

Project A, Project B

Project B wants to call models in Project A...

1) Project B connects to the same database with the same user/login as Project A.

If so then you can just import models from Project A into Project B and interact with them like normal.

2) Project B connects to a different database than Project A.

You can define two databases in the settings file for Project B.

DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': 'postgres_user',
        'PASSWORD': 's3krit'
    },
    'users': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

And then either define a db router so django knows what database to go to to get data for models from Project A

OR

You can explicity set the db to use when making calls the ORM using something like:

Author.objects.using('other').all()

like image 93
jawache Avatar answered Oct 12 '22 11:10

jawache