简体   繁体   中英

Django second DB returns None

To set up the two databases I followed the documentation which includes:

  • Adding the DB information in setting.py DATABASES={}
  • Created a matching model of the model from another DB
  • Run migrate (Which created a blank table for the model in second DB)

    from client_portal.models import client_names

      def try_names(request): cn = client_portal.objects.using('second_db').filter(client_id='170155').last() 

    print(cn.last_name)

cn is None. It shouldn't because the data exists in the second DB. My assumption is it's querying the data from the default db because I missed a step.

Do I need to 'install' a router even if I will use using() exclusively? If so, where do I save the file?

DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']

That example was from the documentation. Where does Django expect the router file?

Thank you for help.

As it turns out, migrate names the tables as [app]_[model_name] and thus with different app names on different projects, I was initially accessing the table migrate --database=created.

To access the table on another server, match the table names on both database servers by using in models.py:

class Meta:
    app_label = [app1_this]
    db_table = [app_another]_[model_name]

If someone else has a better solution, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM