在djang中定义数据库modelwise

2024-04-20 12:08:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想在Django中为define database model wise找到一个解决方案。 就像在我的设置.py有三个数据库

你知道吗设置.py你知道吗

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'db_one': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db_one.sqlite3'),
    },
    'db_two': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db_two.sqlite3'),
    },
}

在我的民意测验中/型号.py你知道吗

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

@python_2_unicode_compatible
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)


    def __str__(self):
        return self.choice_text

现在我想在db\u one数据库中添加问题模型,在db\u two数据库中添加选择模型,那么我该怎么做呢

我试着用路由器遵循这个multiple databases and multiple models in django 但它只偏好默认数据库,之后我尝试在默认数据库中设置空白设置并尝试迁移,但它给了我一个错误

或者

这是在Django中为应用程序定义数据库的方法吗


Tags: pathdjangotextnamepyself数据库db
2条回答

您可以使用数据库myusing方法。你知道吗

例如,从db_one获取所有数据如下所示:

all_data = YourModel.objects.using('db_one').all()

您需要将模型迁移到默认数据库以外的数据库,对吗?你知道吗

您可以在迁移时选择数据库。你知道吗

# database name from settings.py
./manage.py migrate  database=<database-name>

django docs

如果希望在一个数据库中保留一些表,在其他数据库中保留一些表,我建议为每个表创建一个迁移。然后,你就可以跑了

./manage.py migrate <your-app-name> <migration-number>  database=<database-name>

编辑

可以跳过在具有 fake标志的特定数据库中创建特定表。你知道吗

  • 首先,删除所有迁移。你知道吗
  • models.py中注释掉你的Choice模型。你知道吗
  • run manage.py makemigrations=>;假设这创建了迁移001(对于Question模型)
  • 取消对Choice模型在models.py中的注释。你知道吗
  • 再次运行manage.py makemigrations。假设这创建了迁移002(对于Choice模型)
  • run manage.py migrate <app-name> 001 database=db_one=>;这将在db\u one中创建问题模型
  • 运行manage.py migrate <app-name> 001 database=db_two fake=>;这个
    将跳过在db\u two中创建表
  • 运行python manage.py migrate <app-name> 002 database=db_one fake =>;这将跳过在db\u one中创建选项表
  • run python manage.py migrate <app-name> 002 database=db_two=>;这将在db\u two中创建Choice模型。你知道吗

相关问题 更多 >