【问题标题】:Django 2.2: Creating models for multiple databasesDjango 2.2:为多个数据库创建模型
【发布时间】:2019-09-16 15:34:03
【问题描述】:

我是 Django 2.2 的新手,我正在构建一个小项目,其中包括 2 个不由 Django 管理的数据库。一个是新的,另一个是遗留的。我将它们添加到数据库列表中

DATABASES = {
    'default': {
        'ENGINE' :'django.db.backends.mysql',
        'NAME': 'petshows',
        'USER':'somecoolusername',
        'PASSWORD': 'somesecurepassword',
        'HOST': 'localhost',
        'PORT':'3306'
    },
    'pets': {
            'ENGINE' :'django.db.backends.mysql',
            'NAME': 'pets',
            'USER':'mysecureusers',
            'PASSWORD': 'somecoolpassword',
            'HOST': 'localhost',
            'PORT':'3306'
        }
}

我为宠物表演创建了模型,看起来效果很好。但是我需要添加一些模型,以便我可以从第二个数据库“宠物”中读取外键。

My models.py

class ShowPets(models.Model):
    sp_id = models.IntegerField(primary_key=True)
    pet_id = models.IntegerField(blank=True, null=True)
    show_id = models.IntegerField(blank=True, null=True)
    created_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'show_pets'


class Shows(models.Model):
    show_id = models.AutoField(primary_key=True)
    show_name = models.CharField(max_length=145, blank=True, null=True)
    show_date = models.DateField(blank=True, null=True)
    location_id = models.IntegerField(blank=True, null=True)
    org_id = models.IntegerField(blank=True, null=True)
    created_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(blank=True, null=True)

    def show_date_pretty(self):
        return self.show_date.strftime('%b %e %Y')

    class Meta:
        managed = False
        db_table = 'shows'

我想在 pets 数据库中为 Pets、pets 表创建一个模型,但我无法从文档中弄清楚如何能够以模型的形式访问第二个数据库,然后在 pet_id 上进行连接(外键),通过 ShowPets 模型和 show_pets 表(在 petshows 数据库中),从 pets 表(在 pets 数据库中)到 pet_id(主键),以便能够提取诸如 pet_name 等内容。

任何人都可以给我任何关于如何完成此任务的好的提示或链接吗?谢谢!

【问题讨论】:

    标签: django python-3.x django-models


    【解决方案1】:

    Django 不支持 cross database joins 与 django orm。

    https://docs.djangoproject.com/en/2.2/topics/db/multi-db/#cross-database-relations

    但您可以使用.using() 方法手动访问任一数据库进行查询:

    Shows.objects.using('pets').all()
    

    保存时您可以使用可选的using= 参数来定义要使用的数据库:

    show = Shows()
    show.save(using='pets')
    

    附带说明一下,通常的做法是让您的模型名称单数(然后上面的实例创建更有意义)

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 2020-09-11
      • 2014-09-17
      • 2013-04-25
      • 1970-01-01
      • 2019-12-24
      • 2013-09-04
      • 2015-08-27
      相关资源
      最近更新 更多