我正在尝试运行以下抛出
AttributeError:' list'对象没有属性'对象'
script.py
#Get Dota2 Item Rarities
dotaItemRarityUrl = 'http://api.steampowered.com/IEconDOTA2_570/GetRarities/v1?'
dotaItemRarityPayload = {'key': settings.SOCIAL_AUTH_STEAM_API_KEY,
'language': 'en',
}
dotaItemRarityInfo = requests.get(dotaItemRarityUrl, params=dotaItemRarityPayload)
dotaItemRarity = dotaItemRarityInfo.json()
dotaItemRarity = dotaItemRarity['result']['rarities']
print(dotaItemRarity)
#print(dotaItemQualities)
#Populate Database With Item Rarities that do NOT exist already
for rarity in dotaItemRarity:
print rarity
irarityId = rarity['id']
irarityProperName = rarity['localized_name']
irarityInternalName = rarity['name']
irarityColor = rarity['color']
q = dotaItemRarity.objects.filter(rarityId=irarityId)
print q
if len(q) == 0:
newRarity = dotaItemRarity(rarityId=irarityId,
rarityProperName=irarityProperName,
rarityInternalName=irarityInternalName,
rarityColor=irarityColor)
newRarity.save()
models.py
class dotaItemRarity(models.Model):
rarityId = models.IntegerField(max_length=3,primary_key=True)
rarityProperName = models.CharField(max_length=60)
rarityInternalName = models.CharField(max_length=50)
rarityColor = models.CharField(max_length=30)
def __unicode__(self):
return self.rarityInternalName
我正在使用南方来处理迁移,并尝试了多种方法来修复此问题,例如删除表并重建它们。据我所知,这应该有效,任何人都可以指出我正确的方向。
答案 0 :(得分:1)
dotaItemRarity
是一个列表,它没有objects
属性:
q = dotaItemRarity.objects.filter(rarityId=irarityId)
那是因为你将它绑定到JSON结果的列表中:
dotaItemRarity = dotaItemRarityInfo.json()
dotaItemRarity = dotaItemRarity['result']['rarities']
Django模型不,正如您所期望的那样。
如果您将dotaItemRarity
Django模型导入script.py
,则该名称不再绑定到该模型,因为您将其替换为列表。
重命名列表以使用不掩盖模型的其他名称。
请注意,Python style guide建议您为类(包括Django模型)使用CamelCase名称,以避免此类错误。
遵循PEP 8稍微重构您的代码,以及使用更清晰的命名实践:
models.py
:
class DotaItemRarity(models.Model):
rarity_id = models.IntegerField(max_length=3, primary_key=True)
rarity_proper_name = models.CharField(max_length=60)
rarity_internal_name = models.CharField(max_length=50)
rarity_color = models.CharField(max_length=30)
def __unicode__(self):
return self.rarity_internal_name
script.py
:
#Get Dota2 Item Rarities
url = 'http://api.steampowered.com/IEconDOTA2_570/GetRarities/v1'
payload = {'key': settings.SOCIAL_AUTH_STEAM_API_KEY, 'language': 'en'}
response = requests.get(url, params=payload)
rarities = response.json()['result']['rarities']
for rarity in rarities:
rarity_id = rarity['id']
try:
DotaItemRarity.get(rarity_id=rarity_id)
except DotaItemRarity.DoesNotExist:
new_rarity = DotaItemRarity(
rarityId=rarity_id,
rarity_proper_name=rarity['localized_name'],
rarity_internal_name=rarity['name'],
rarity_color=rarity['color'])
new_rarity.save()