Djago 可以创建一个 returns 字典的数据库查询吗?

Can Djago create a database query that returns a dictionary of dictionaries?

Djago 可以创建 returns 字典的数据库查询吗?

该模型包含一个外键。使用这些键,我想整理出查询结果。然后我想使用休息框架提供这些结果。

插画模特:

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),
        )
    )

查看:

class RecordListAPIView(generics.ListAPIView):
    queryset = Record.objects.all()
    serializer_class = RecordSerializer

    def get_queryset(self):
        return Record.objects.all()

如何编辑查询以获得此结果?

{
    "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
        }
    ]
}
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()

然后将此视图添加到您的 urls.py 等...

那么当你的 Evse 对象被序列化时,报告也会被序列化