Can Djago create a database query that returns a dictionary of dictionaries?
The model contains a foreign key. Using these keys, I would like to have the query results sorted out. I would then like to provide these results using a rest framework.
Illustration model:
class Record(BaseModel):
evse = models.ForeignKey(
'core.Evse',
verbose_name=_('EVSE'),
related_name='record_evse',
on_delete=models.CASCADE,
)
current_rms_p1 = models.FloatField(
_('Current RMS P1'),
default=0,
validators=(
MinValueValidator(0),
MaxValueValidator((2**16 - 1) * 0.1),
)
)
current_rms_p2 = models.FloatField(
_('Current RMS P2'),
default=0,
validators=(
MinValueValidator(0),
MaxValueValidator((2**16 - 1) * 0.1),
)
)
current_rms_p3 = models.FloatField(
_('Current RMS P3'),
default=0,
validators=(
MinValueValidator(0),
MaxValueValidator((2**16 - 1) * 0.1),
)
)
View:
class RecordListAPIView(generics.ListAPIView):
queryset = Record.objects.all()
serializer_class = RecordSerializer
def get_queryset(self):
return Record.objects.all()
How to edit a query to get this result?
{
"evse 1": [
{
"current_rms_p1": 0.0,
"current_rms_p2": 0.0,
"current_rms_p3": 0.0
},
{
"current_rms_p1": 0.0,
"current_rms_p2": 0.0,
"current_rms_p3": 0.0
}
],
"evse 2": [
{
"current_rms_p1": 0.0,
"current_rms_p2": 0.0,
"current_rms_p3": 0.0
}
]
}
CodePudding user response:
class EVSESerializer(serializers.ModelSerializer):
record_evse = RecordSerializer(read_only=True, many=True)
class Meta:
model = Evse
fields = '__all__'
class EvseListAPIView(generics.ListAPIView):
queryset = Evse.objects.prefetch_related()
serializer_class = EVSESerializer
def get_queryset(self):
return Evse.objects.all()
Then add this view to your urls.py etc...
Then when you Evse objects will be serialized, the reports will be serialized too