I’ve created a function in my serializers.py
that call an external API and give me a dict back.
How can I use the output from return downloads
in the get_all_files
as a field in class Meta
?
After the first answer, I’ve got the following error message:
JavaScript
x
3
1
Exception Value: 'NoneType' object is not subscriptable
2
Exception Location: /app/api/serializers.py, line 68, in get_all_files
3
Line 68 is the following: return get_all_files(instance.bands)
serializers.py
JavaScript
1
79
79
1
from rest_framework import serializers
2
from . import views
3
from api.models import Application, Indice, Satellite, Band
4
from satsearch import Search
5
6
class IndiceSerializer(serializers.ModelSerializer):
7
8
class Meta:
9
model = Indice
10
fields = ['name', 'accr', 'description', 'is_NormalizedDifference', 'calc', ]
11
12
class SatelliteSerializer(serializers.ModelSerializer):
13
14
class Meta:
15
model = Satellite
16
fields = ['name', 'accr', 'operator', ]
17
18
class BandSerializer(serializers.ModelSerializer):
19
20
class Meta:
21
model = Band
22
fields = ['band', 'description', 'wavelength', 'resolution', ]
23
24
class OsdSerializer(serializers.ModelSerializer):
25
bands = BandSerializer(source='indice_to_use.needed_bands', many=True)
26
satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use')
27
indice = IndiceSerializer(source='indice_to_use')
28
files = serializers.SerializerMethodField()
29
30
def get_files(self, instance):
31
def get_all_files(bands):
32
# configuration
33
url = 'https://earth-search.aws.element84.com/v0' # URL to Sentinel 2 AWS catalog
34
collection = 'sentinel-s2-l2a-cogs'
35
36
# search parameter
37
startDate = '2021-04-10'
38
endDate = '2021-04-12'
39
location = [ 13.6677,
40
43.7232,
41
16.2605,
42
45.4522
43
]
44
45
bbox_search = Search(
46
bbox=location,
47
datetime=startDate+"/"+endDate,
48
query={'eo:cloud_cover': {'lt': 50}},
49
collections=[collection],
50
url=url,
51
sort={'field': 'eo:cloud_cover', 'direction': 'desc'},
52
)
53
54
items = bbox_search.items()
55
56
downloads = {}
57
58
for i, item in enumerate(items):
59
60
data = {}
61
62
data['Product ID']= item.properties["sentinel:product_id"]
63
data['Preview']= item.asset("thumbnail")["href"]
64
data['Date']= item.properties["datetime"]
65
data['Cloud cover']= item.properties["eo:cloud_cover"]
66
67
for band in bands.split(','):
68
data[band] = item.asset(band)["href"]
69
70
downloads[i] = data
71
72
return downloads
73
74
return get_all_files(instance.bands)
75
76
class Meta:
77
model = Application
78
fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'files', ]
79
Advertisement
Answer
The code works fine. The error was caused by a mistake in my backend. The key of the sat-search result was in 3 digest, e.g. B03
. The content in my field was in two digst, e.g. B3
. That’s why the matching doesn’t worked.