From 7cbc2b4193131ded8d4efbadf6269c6263b1428d Mon Sep 17 00:00:00 2001 From: juuso-j Date: Wed, 13 Sep 2023 07:52:06 +0300 Subject: [PATCH 1/2] Test data_from_year field --- eco_counter/tests/test_api.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eco_counter/tests/test_api.py b/eco_counter/tests/test_api.py index 8f0afc7bb..9e7fc2ce7 100644 --- a/eco_counter/tests/test_api.py +++ b/eco_counter/tests/test_api.py @@ -3,6 +3,7 @@ import pytest from rest_framework.reverse import reverse +from .conftest import TEST_TIMESTAMP from .constants import TEST_EC_STATION_NAME @@ -271,6 +272,7 @@ def test__station(api_client, stations, year_datas): assert response.status_code == 200 assert response.json()["results"][0]["name"] == TEST_EC_STATION_NAME assert response.json()["results"][0]["sensor_types"] == ["at"] + assert response.json()["results"][0]["data_from_year"] == TEST_TIMESTAMP.year # Test retrieving station by data type url = reverse("eco_counter:stations-list") + "?data_type=a" response = api_client.get(url) From 24fb14b8ec6b385a5c70e3b0ac54d2c8253e08d8 Mon Sep 17 00:00:00 2001 From: juuso-j Date: Wed, 13 Sep 2023 08:16:38 +0300 Subject: [PATCH 2/2] Serialize data_from_year field --- eco_counter/api/serializers.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/eco_counter/api/serializers.py b/eco_counter/api/serializers.py index d81362679..ea095df18 100644 --- a/eco_counter/api/serializers.py +++ b/eco_counter/api/serializers.py @@ -1,3 +1,4 @@ +from django.db.models import Q from rest_framework import serializers from ..models import ( @@ -35,6 +36,7 @@ class StationSerializer(serializers.ModelSerializer): lon = serializers.SerializerMethodField() lat = serializers.SerializerMethodField() sensor_types = serializers.SerializerMethodField() + data_from_year = serializers.SerializerMethodField() class Meta: model = Station @@ -52,6 +54,7 @@ class Meta: "lon", "lat", "sensor_types", + "data_from_year", ] def get_y(self, obj): @@ -79,6 +82,19 @@ def get_sensor_types(self, obj): result.append(type) return result + def get_data_from_year(self, obj): + q_exp = ( + Q(value_at__gt=0) + | Q(value_pt__gt=0) + | Q(value_jt__gt=0) + | Q(value_bt__gt=0) + ) + qs = YearData.objects.filter(q_exp, station=obj).order_by("year__year_number") + if qs.count() > 0: + return qs[0].year.year_number + else: + return None + class YearSerializer(serializers.ModelSerializer): station_name = serializers.PrimaryKeyRelatedField(