在 Django 中访问嵌套值
Accessing nested values in Django
我正在尝试从 API 访问我的 Django 模板(使用 Jinja2)中的值,但遇到了一些困难。我是 Python/Django/programming 的新手,很难浏览 lists/dicts.
这个复杂的嵌套结构
这是单个航班的 API 响应的片段(响应总共包含 250 个航班):
{
"meta": {
"count": 2
},
"data": [
{
"type": "flight-offer",
"id": "1",
"source": "GDS",
"instantTicketingRequired": false,
"nonHomogeneous": false,
"oneWay": false,
"lastTicketingDate": "2020-11-20",
"numberOfBookableSeats": 2,
"itineraries": [
{
"duration": "PT22H40M",
"segments": [
{
"departure": {
"iataCode": "GIG",
"terminal": "2",
"at": "2020-12-01T16:30:00"
},
"arrival": {
"iataCode": "CDG",
"terminal": "2E",
"at": "2020-12-02T07:45:00"
},
"carrierCode": "AF",
"number": "443",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "AF"
},
"duration": "PT11H15M",
"id": "3",
"numberOfStops": 0,
"blacklistedInEU": false
},
{
"departure": {...
对于每个航班,我想提取以下内容key/values:
- id
- 持续时间
- iata代码
以下是我到目前为止尝试过的...
id(成功)
{% for flight in data %}
{{ flight.id }}
{% endfor %}
iataCode(未成功)
{% for flight in data %}
{% for itinerary in itineraries %}
{% for segment in segments %}
{{ departure.iataCode }}
{% endfor %}
{% endfor %}
{% endfor %}
iataCode(未成功)
{% for itineraries, itinerary in data %}
{% for segments, segment in itineraries %}
{{ departure.iataCode }}
{% endfor %}
{% endfor %}
{% endblock %}
非常感谢此处的任何建议。
谢谢!
您必须“遵循”循环变量。
{% for flight in data %}
{% for itinerary in flight.itineraries %}
{% for segment in itinerary.segments %}
{{ segment.departure.iataCode }}
{% endfor %}
{% endfor %}
{% endfor %}
我正在尝试从 API 访问我的 Django 模板(使用 Jinja2)中的值,但遇到了一些困难。我是 Python/Django/programming 的新手,很难浏览 lists/dicts.
这个复杂的嵌套结构这是单个航班的 API 响应的片段(响应总共包含 250 个航班):
{
"meta": {
"count": 2
},
"data": [
{
"type": "flight-offer",
"id": "1",
"source": "GDS",
"instantTicketingRequired": false,
"nonHomogeneous": false,
"oneWay": false,
"lastTicketingDate": "2020-11-20",
"numberOfBookableSeats": 2,
"itineraries": [
{
"duration": "PT22H40M",
"segments": [
{
"departure": {
"iataCode": "GIG",
"terminal": "2",
"at": "2020-12-01T16:30:00"
},
"arrival": {
"iataCode": "CDG",
"terminal": "2E",
"at": "2020-12-02T07:45:00"
},
"carrierCode": "AF",
"number": "443",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "AF"
},
"duration": "PT11H15M",
"id": "3",
"numberOfStops": 0,
"blacklistedInEU": false
},
{
"departure": {...
对于每个航班,我想提取以下内容key/values:
- id
- 持续时间
- iata代码
以下是我到目前为止尝试过的...
id(成功)
{% for flight in data %}
{{ flight.id }}
{% endfor %}
iataCode(未成功)
{% for flight in data %}
{% for itinerary in itineraries %}
{% for segment in segments %}
{{ departure.iataCode }}
{% endfor %}
{% endfor %}
{% endfor %}
iataCode(未成功)
{% for itineraries, itinerary in data %}
{% for segments, segment in itineraries %}
{{ departure.iataCode }}
{% endfor %}
{% endfor %}
{% endblock %}
非常感谢此处的任何建议。
谢谢!
您必须“遵循”循环变量。
{% for flight in data %}
{% for itinerary in flight.itineraries %}
{% for segment in itinerary.segments %}
{{ segment.departure.iataCode }}
{% endfor %}
{% endfor %}
{% endfor %}