Django Rest Framework returning duplicate data when returning a nested json response
I have a pricing table that contains the following fields: id
, date
, price_non_foil
, price_foil
, card_id
. This table holds pricing data for each card for each day. For Example:
"23a6c413-7818-47a8-9bd9-6de7c328f103" | "2021-12-08" | 0.24 | 0.80 | "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" |
"c51a72ab-f29f-4465-a210-ff38b15e83a1" | "2021-12-05" | 1.27 | 0.80 | "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" |
"17289b71-3b73-4e16-a479-25a7069a142e" | "2021-12-09" | 0.38 | 0.80 | "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" |
"fa88f619-ec32-4550-9a57-c77b6e1a8e11" | "2021-12-07" | 1.27 | 0.80 | "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" |
"f996d6cb-7d98-415c-bd70-2fca8f4e03a5" | "2021-12-06" | 1.27 | 0.80 | "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" |
"2f8c00f3-4d47-478d-a653-7d7a476e9bae" | "2021-12-09" | 0.43 | 3.33 | "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" |
"15b20912-4103-4e08-8f91-fed820b761af" | "2021-12-05" | 0.66 | 5.08 | "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" |
Currently there is pricing data for 5 dates for each card. I am trying to create an endpoint to return the latest 2 prices for each card using Django rest framework. I have managed to get the response to be nest under the card id, but my issue is that it returns multiple card ids, I assume based on the number of pricing data records for each card.
views.py
class individual_set_pricing(ListAPIView):
serializer_class = SerializerSetsIndividualPricing
def get_queryset(self):
code = self.kwargs.get('code', None)
qs = magic_sets_cards_pricing.objects.filter(card_id__set_id__code=code.upper()).values('card_id')
return qs
serializers.py
class SerializerSetsIndividualPricing(serializers.ModelSerializer):
card = serializers.SerializerMethodField('get_card')
class Meta:
model = magic_sets_cards_pricing
fields = ['card_id', 'card']
def get_card(self, obj):
date = magic_sets_cards_pricing.objects.filter(card_id=obj['card_id']).values('date', 'price_non_foil', 'price_foil').order_by('-date')[:2]
return date
Response
[
{
"card_id": "3a261180-c1b3-4641-9524-956be55bee7a",
"card": [
{
"date": "2021-12-09",
"price_non_foil": 1.15,
"price_foil": 1.54
},
{
"date": "2021-12-08",
"price_non_foil": 0.43,
"price_foil": 1.62
}
]
},
{
"card_id": "3a261180-c1b3-4641-9524-956be55bee7a",
"card": [
{
"date": "2021-12-09",
"price_non_foil": 1.15,
"price_foil": 1.54
},
{
"date": "2021-12-08",
"price_non_foil": 0.43,
"price_foil": 1.62
}
]
},
...
how to I remove the duplicate records in the json response?