I am using a third-party API to get data and add it into my database via objects.update_or_create()
method. This data has many records and some of the fields in the response only exists for certain records.
Below the a snippet of the JSON that is returned from the API. However this data is only present for some of the records in the JSON response. When I try to add this data into my model, I am getting the following error:
'f_name': i.get('card_faces')[0].get('name'),
TypeError: 'NoneType' object is not subscriptable
I am trying to have it so that if the card_faces
field exists, True
is added to the card_face
column in the database, and then the card_faces
name
to the database. If card_faces
doesn't exist, then False
is added to the card_face
column in the database, and subsequent fields are null.
JSON:
{
"data": [
{
"name": "Emeria Captain"
},
{
"name": "Emeria's Call // Emeria, Shattered Skyclave",
"card_faces": [
{
"object": "card_face",
"name": "Emeria's Call"
},
{
"object": "card_face",
"name": "Emeria, Shattered Skyclave"
}
]
}
]
}
views.py:
for i in card_data:
Card.objects.update_or_create(
id=i.get('id'),
defaults={
'name': i.get('name'),
'card_faces': i.get('card_faces'),
'f_name': i.get('card_faces')[0].get('name'),
'b_name': i.get('card_faces')[1].get('name'),
}
)
If the card_faces field doesn't exist, then the result of .get('card_faces')
will be None , which you can't then call index 0 on
Break apart your line and do a logic check instead - this solution assumes that if card_faces does exist, there will be an index 0 and 1; you haven't provided enough information to assume otherwise
card_faces = i.get('card_faces')
f_name = None
b_name = None
if card_faces:
f_name = card_faces[0].get('name')
b_name = card_faces[1].get('name')
defaults = {
'name': i.get('name'),
'card_faces': True if card_faces else False,
'f_name': f_name,
'b_name': b_name,
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.