0
我試圖在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),
),
]
由於yahooticketsymbol已經有'null = True',所以看起來你不會打破任何外鍵約束。如果'PriceHistory'沒有'YahooTicketSymbol',它將被設置爲'null'。您在遷移數據庫時是否遇到問題? –
是的。那是對的。當我嘗試運行「遷移」命令時,Django不斷拋出錯誤。 – Cloud
您可以發佈用於添加外鍵的遷移源嗎? –