2017-02-21 44 views
-2

我有兩個表:如何通過外鍵選擇特定行?

class symbol(models.Model): 
    ticker = models.CharField(max_length=40) 
    instrument = models.CharField(max_length=64, default='stock') 
    name = models.CharField(max_length=200) 
    sector = models.CharField(max_length=200, default=None) 
    currency = models.CharField(max_length=64, default='USD') 
    created_date = models.DateTimeField(auto_now=True) 
    last_updated_date = models.DateTimeField(auto_now=True) 

class daily_price(models.Model): 
    symbol = models.ForeignKey(symbol) 
    price_date = models.DateTimeField() 
    created_date = models.DateTimeField() 
    last_updated_date = models.DateTimeField() 
    open_price = models.DecimalField(max_digits=19, decimal_places=4) 
    high_price = models.DecimalField(max_digits=19, decimal_places=4) 
    low_price = models.DecimalField(max_digits=19, decimal_places=4) 
    close_price = models.DecimalField(max_digits=19, decimal_places=4) 
    adj_close_price = models.DecimalField(max_digits=19, decimal_places=4) 
    volume = models.BigIntegerField() 

我要選擇表strategyceleryapp_daily_price的行。

我想symbol's ticker(外鍵)使用read_sql_query來選擇特定的行

con = sqlite3.connect("/home/leo/github/StrategyCeleryWebsite/db.sqlite3") 
df = pd.read_sql_query("SELECT * from strategyceleryapp_daily_price", con) 

# verify that result of SQL query is stored in the dataframe 
print(df.head()) 

con.close() 

在Django,我可以使用daily_price.objects.get(symbol__ticker='AAPL')

但我不知道如何從sql命令寫入命令​​。

我應該怎麼寫這個命令?

非常感謝。

+1

你爲什麼使用'sqlite3.connect'?你知道基於** _ ORM(Object-relational mapping)_ **的Django嗎? –

+0

是的,我知道ORM。但是這個代碼是由純python運行的。謝謝。 – yensheng

+0

這個怎麼樣:https://docs.python.org/2/library/sqlite3.html –

回答

0

在SQL,您加入表格和檢查值:

SELECT dp.* from strategyceleryapp_daily_price dp INNER JOIN strategyceleryapp_symbol s on dp.symbod_id=s.id where s.ticker='AAPL' 

您可以檢查的Django與創建查詢:

python manage.py dbshell 

然後:

print(daily_price.objects.get(symbol__ticker='AAPL').query) 
+0

你會得到回溯'AttributeError:'daily_price'對象沒有屬性'query'','.query'只能用於queryset,不能用'.get()'。例如'daily_price.objects.filter(symbol__ticker ='AAPL')。query .__ str __()' –