在我的项目中,我有一个与Coin模型具有一对多关系的Transaction模型。每笔交易都有一个buy_price和unit_number(单位数量)。借助下面views.py
中的嵌套for循环,我希望在每个硬币字典中生成一个多个buy_price的列表。
单独查询(使用硬编码的硬币名称)将输出我期望的多个buy_prices数据-实际上是数据库中的数据。但是,一旦我将所有代码放在一起,我得到的只是每个硬币的一个buy_price--print(coin_list)
我在做什么错了?
views.py:
from django.shortcuts import render
import requests
from .models import Coin, Transaction
from decimal import Decimal
def index(request):
coin_list = []
coins = Coin.objects.all()
url = 'https://api.coingecko.com/api/v3/coins/{}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false'
for coin in coins:
db_coin_name = coin.name
coin_data = requests.get(url.format(db_coin_name)).json()
api_current_price = Decimal(coin_data['market_data']['current_price']['eur'])
coin_dict = {
'official_name': coin_data['name'],
'symbol': coin_data['symbol'],
'image': coin_data['image']['large'],
}
transactions = Transaction.objects.filter(coin__name=f"{db_coin_name}")
for t in transactions:
buy_prices = []
buy_prices.append(t.buy_price)
print(buy_prices)
coin_dict['transactions'] = {
'buy_prices': buy_prices
}
coin_list.append(coin_dict)
print(coin_list)
context = {'data': coin_list}
return render(request, 'cryptodashboard/index.html', context)
print(buy_prices)
的终端输出-前两个属于zcash,后两个属于恒星
[Decimal('10')]
[Decimal('5')]
[Decimal('0.189442')]
[Decimal('0.170867')]
print(coin_list)
的终端输出
[
{
'official_name':'Zcash',
'symbol':'zec',
'image':'https://assets.coingecko.com/coins/images/486/large/circle-zcash-color.png?1534468310',
'transactions':{
'buy_prices':[
Decimal('5')
]
}
},
{
'official_name':'Stellar',
'symbol':'xlm',
'image':'https://assets.coingecko.com/coins/images/100/large/stellar_lumens.png?1510040249',
'transactions':{
'buy_prices':[
Decimal('0.170867')
]
}
}
]
P.S让我知道是否需要提供其他代码段。一直为此苦苦挣扎,因此,非常感谢您的帮助!
答案 0 :(得分:2)
我认为问题出在这里
for t in transactions:
buy_prices = [] # <-- here
buy_prices.append(t.buy_price)
print(buy_prices)
coin_dict['transactions'] = {
'buy_prices': buy_prices
}
每次在事务中开始新的迭代时,您都会创建一个新列表。
所以也许你可以这样:
buy_prices = []
for t in transactions:
buy_prices.append(t.buy_price)
coin_dict['transactions'] = {
'buy_prices': buy_prices
}
更好:
coin_dict['transactions'] = { 'buy_prices': list(transactions.values_list('buy_prices', flat=True))}
# No need for Transaction for loop