Настройка вывода json, возвращающего первый элемент из списка на Django Rest Framework
У меня есть API, который возвращает следующий json:
{
"id": 6,
"lot_no": "787878",
"product_id": "116110",
"assay_type": "reascan_crp",
"valid_from": "2022-11-21",
"expiry_date": "2022-11-27",
"is_active": true,
"last_modified": "2022-11-21T14:29:32.435307Z",
"teststrips": [
{
"number": 1,
"name": "",
"control_line_threshold": 1.0,
"testlines": [
null,
null
]
}
],
"parameters": [
{
"a": -3.0,
"b": -4.0,
"c": -6.0,
"d": -9.0
}
]
},
однако я хочу получить следующий вывод без списка параметров:
{
"id": 6,
"lot_no": "787878",
"product_id": "116110",
"assay_type": "reascan_crp",
"valid_from": "2022-11-21",
"expiry_date": "2022-11-27",
"is_active": true,
"last_modified": "2022-11-21T14:29:32.435307Z",
"teststrips": [
{
"number": 1,
"name": "",
"control_line_threshold": 1.0,
"testlines": [
null,
null
]
}
],
"parameters":
{
"a": -3.0,
"b": -4.0,
"c": -6.0,
"d": -9.0
}
},
serializers.py :
class ParametersSerializer(serializers.ModelSerializer):
class Meta:
model = TeststripConfiguration
fields = ('a', 'b', 'c', 'd')
class TeststripSerializer(serializers.ModelSerializer):
testlines = serializers.SerializerMethodField()
class Meta():
model = TeststripConfiguration
fields = ('number', 'name', 'control_line_threshold', 'testlines')
def get_testlines(self, teststrip):
upper_negative_testline = None
lower_positive_testline = None
if str(teststrip.batch.assay_type) != "reascan_crp":
upper_negative_testline = teststrip.testlines.values('upper_negative_threshold')[0]['upper_negative_threshold']
lower_positive_testline = teststrip.testlines.values('lower_positive_threshold')[0]['lower_positive_threshold']
return upper_negative_testline, lower_positive_testline
class BatchSerializer(serializers.ModelSerializer):
parameters = ParametersSerializer(source='teststrips', many=True, read_only=True)
teststrips = TeststripSerializer(many=True, read_only=True)
assay_type = serializers.SlugRelatedField(
read_only=True,
slug_field='name'
)
product_id = serializers.ReadOnlyField()
class Meta():
model = Batch
fields = ('id', 'lot_no', 'product_id', 'assay_type', 'valid_from', 'expiry_date',
'is_active', 'last_modified', 'teststrips', 'parameters')
views.py:
class CustomPaginator(pagination.PageNumberPagination):
page_size = 25
class BatchesUpdatedView(ListAPIView, mixins.ListModelMixin):
"""API view to return all batches, their related teststrips and testlines"""
serializer_class = BatchSerializer
pagination_class = CustomPaginator
def get_queryset(self):
return Batch.objects.all()
def get(self, request, *args, **kwargs):
api_latest_update = self.request.query_params.get('latest_update', None)
if api_latest_update is not None:
try:
latest_update = parse_datetime(api_latest_update)
if latest_update is None:
raise TypeError
except TypeError:
return Response(
{'Error': "Invalid datetime, please make sure it is URL encoded"},
status=status.HTTP_400_BAD_REQUEST)
if not self.has_batches_been_updated(latest_update):
return Response(status=status.HTTP_304_NOT_MODIFIED)
response = self.list(request, *args, **kwargs)
latest_update = Batch.objects.latest_modified_date()
if latest_update is None:
response['X-LATEST-UPDATE'] = None
else:
response['X-LATEST-UPDATE'] = Batch.objects.latest_modified_date().isoformat()
return response
def has_batches_been_updated(self, latest_update) -> bool:
return True if latest_update < Batch.objects.latest_modified_date() else False
Я пытался изменить parameters = ParametersSerializer(source='teststrips', many=True, read_only=True) на parameters = ParametersSerializer(source='teststrips', many=False, read_only=True), но он возвращает null в качестве значений a,b,c,d.
edit
teststrips model.py:
class TeststripConfiguration(models.Model):
"""The Teststrip Configuration for applying thresholds on batches."""
batch = models.ForeignKey('ndx_batch.Batch', on_delete=models.CASCADE, related_name='teststrips')
number = models.IntegerField(null=True, blank=False)
name = models.CharField(_("name"), blank=True, null=False, max_length=120)
control_line_threshold = models.FloatField(_("control line threshold"), null=True)
a = models.FloatField(_("A"), blank=True, null=True, default=0)
b = models.FloatField(_("B"), blank=True, null=True, default=0)
c = models.FloatField(_("C"), blank=True, null=True, default=0)
d = models.FloatField(_("D"), blank=True, null=True, default=0)
class Meta: # noqa
ordering = ('batch',)
verbose_name = _('teststrip configuration')
verbose_name_plural = _('teststrip configurations')
def __repr__(self) -> str:
return 'TeststripConfiguration(pk={!r})'.format(self.pk)
def __str__(self) -> str:
return '{}'.format(self.name)
Любая помощь будет оценена по достоинству! Спасибо