0

I want to read data from an external database and generate reports in Django. I am trying to create the required models for the data that I will be fetching. Is it possible to define relationships when doing this?

For example:

I have 2 tables, ITEMS and STAKEHOLDERS, each ITEM has many STAKEHOLDERS. Is it possible to define the models such that, when I do, ITEM.objects.get(pk = 1).STAKEHOLDERS, I get all the stakeholders for that specific item?

Some additional details: I will be using custom sql to fetch the data for an ITEM and Stakeholder.

1 Answer 1

1

You'll need a database router to direct queries on these models to the desired database.

class Item(Model):
    _database = 'legacy'

    # fields...


class Stakeholder(Model):
    _database = 'legacy'

    item = ForeignKeyField(Item, related_name='stakeholders')
    # fields...

# ...

Item.objects.get(pk=1).stakeholders

# ...

class DbRouter(object):

    def db_for_read(self, model, **hints):
        database = getattr(model, '_database', None)
        if database:
            return database
        else:
            return 'default'

    # Implement other methods if needed (e.g. db_for_write)

# settings.py
DATABASE_ROUTERS = ['myapp.mymodule.DbRouter']
Sign up to request clarification or add additional context in comments.

4 Comments

I know this works for the default database, but, if I have a second legacy database, would this still work?
@Dasith you mean, for example, Item belonging to a database A and stakeholder belonging to a database B?
No, both in same database, but I will be using custom sql to fetch the data in the model.
@Dasith I think I get it. See if the updated answer is what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.