Reputation: 37
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays.
I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26.
views.py
class weatherDetail(APIView):
def get_object(self, city_name, ndays):
try:
x = weatherdata.objects.filter(city_name__icontains=city_name)
now = datetime.datetime.now()
fromdate = now - timedelta(days=ndays)
y =
return x
except Snippet.DoesNotExist:
raise Http404
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_object(city_name,ndays)
serializer = weatherdataserializer(snippet,many =True)
return Response(serializer.data)
models.py
class weatherdata(models.Model):
city_name = models.CharField(max_length = 80)
city_id = models.IntegerField(default=0)
latitude = models.FloatField(null=True , blank=True)
longitude = models.FloatField(null=True , blank=True)
dt_txt = models.DateTimeField()
temp = models.FloatField(null = False)
temp_min = models.FloatField(null = False)
temp_max = models.FloatField(null = False)
pressure = models.FloatField(null = False)
sea_level = models.FloatField(null = False)
grnd_level = models.FloatField(null = False)
humidity = models.FloatField(null = False)
main = models.CharField(max_length=200)
description = models.CharField(max_length=30)
clouds = models.IntegerField(null=False)
wind_speed = models.FloatField(null = False)
wind_degree = models.FloatField(null = False)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('weatherdata/', views.weatherList.as_view()),
path('weatherdata/<str:city_name>/<int:ndays>/', views.weatherDetail.as_view()),
]
I want 'y' to be filtering objects based on dates. previous ndays data has to be returned. get_object should return the objects which falls under both x and y what needs to be modified in my code.
Upvotes: 2
Views: 56
Reputation: 11665
You have to change your query like below
class weatherDetail(APIView):
def get_queryset(self, city_name, ndays):
x = weatherdata.objects.filter(city_name__icontains=city_name)
today_date = timezone.now().date()
fromdate = today_date - timedelta(days=ndays)
x = x.filter(dt_txt__gte=fromdate).order_by('dt_txt')
return x
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_queryset(city_name, ndays)
serializer = weatherdataserializer(snippet, many=True)
return Response(serializer.data)
Upvotes: 1