与包含记录的预先存在的数据库建立一对多关系

时间:2016-01-24 16:08:06

标签: django django-models

我正在尝试在YahooTickerSymbol和PriceHistory数据库之间创建一对多关系。但是,我已经在PriceHistory数据库中有一些数据,没有任何与YahooTickerSymbol数据库相关的密钥。有没有办法在不违反外键约束的情况下创建关系?

class YahooTickerSymbols(models.Model):
    yahoo_ticker_number = models.AutoField(primary_key=True, )
    yahoo_ticker_symbol = models.CharField(max_length=20, )
    yahoo_company_name = models.CharField(max_length=120, )

    class Meta:
        ordering = ['yahoo_company_name', ]
        verbose_name_plural = "Yahoo Ticker Symbols"

    def __str__(self):
        return "%s is %s." % (self.yahoo_company_name, self.yahoo_ticker_symbol)

class PriceHistory(models.Model):
    price_data_number = models.AutoField(primary_key=True, )
    yahoo_ticker_symbol = models.CharField(max_length=20, )
    price_date = models.DateField(auto_now=False, auto_now_add=False, )
    price_open = models.DecimalField(max_digits=7, decimal_places=3, )
    price_high = models.DecimalField(max_digits=7, decimal_places=3, )
    price_low = models.DecimalField(max_digits=7, decimal_places=3, )
    price_close = models.DecimalField(max_digits=7, decimal_places=3, )
    price_adjusted_close = models.DecimalField(max_digits=7, decimal_places=3, )
    price_volume = models.BigIntegerField()
    yahootickersymbol = models.ForeignKey(YahooTickerSymbols, blank=True, null=True,
                                          on_delete=models.SET_NULL, )

    class Meta:
        ordering = ['yahoo_ticker_symbol', 'price_date', ]
        verbose_name_plural = "Historical Prices"

    def __str__(self):
        return "%s - %s : %s" % (self.yahoo_ticker_symbol, self.price_date, self.price_close)

迁移文件中的代码如下:

class Migration(migrations.Migration):

    dependencies = [
        ('investments', '0009_auto_20160124_1517'),
    ]

    operations = [
        migrations.AlterField(
            model_name='pricehistory',
            name='yahootickersymbol',
            field=models.ForeignKey(to='investments.YahooTickerSymbols', on_delete=django.db.models.deletion.SET_NULL, null=True, blank=True),
        ),
    ]

1 个答案:

答案 0 :(得分:0)

我意识到在运行makemigrations命令的过程中我犯了一个错误。

以前,我没有为null=True设置models.ForeignKey,而是运行了makemigrations命令。在意识到我的错误后,我在null=True中添加了models.py。但是,我没有删除以前的迁移文件。因此,Django一直试图运行旧的迁移文件,即使这些文件不可能生效。

要解决此问题,您需要运行showmigrations以了解未包含哪些迁移文件,以了解问题的根源。