如何通过外键选择特定行?

时间:2017-02-21 07:58:22

标签: python sqlite

我有两张桌子:

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()

我想选择table strategyceleryapp_daily_price&#39行。

我想使用read_sql_query按symbol's ticker(外键)选择特定行

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 个答案:

答案 0 :(得分: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)