我有几个Django应用程序,他们需要在Heroku上共享一个数据库。我可以在每个需要访问它的语句上指定共享数据库,例如:
from account.models import User
if DEBUG: # Running locally
users = User.objects.all() # 'default' DB
else: # Running on Heroku
users = User.objects.using('shared').all() # 'shared' DB
我有两个问题:
1)在每个语句中指定shared
数据库真的很乏味。是否可以为所有人设置shared
数据库(可能在setting.py
)?例如:
from account.models import User
if not DEBUG: # Running on Heroku
User = User.objects.using('share') # This is hypothetical!!
users = User.objects.all()
2)如何为外键设置shared
DB。例如:
from account.models import User
class Article(models.Model):
author = models.ForeignKey(User) # How to set 'User' to come from 'shared' DB?
答案 0 :(得分:1)
https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#using-routers \
https://docs.djangoproject.com/en/dev//topics/db/multi-db/#limitations-of-multiple-databases
我建议您最初尝试将所有内容保存在1个数据库中。通常在开始时不需要将其分开。