gpt4 book ai didi

django - 如何通过 Django 中的模型属性之一对对象数组进行分组?

转载 作者:行者123 更新时间:2023-12-05 04:49:23 25 4
gpt4 key购买 nike

我想做类似于此示例的操作 How to group an array of objects by key但我在 Django 中找不到 API Get 的解决方案。

这是我所拥有的示例:

[
{
"id": 1,
"nutrition_measurement_id": "1",
"nutrition_type_id": "2",
"feeding_time": "dinner"
},
{
"id": 2,
"nutrition_measurement_id": "2",
"nutrition_type_id": "1",
"feeding_time": "dinner"
},
{
"id": 3,
"nutrition_measurement_id": "3",
"nutrition_type_id": "2",
"feeding_time": "breakfast"
},
{
"id": 4,
"nutrition_measurement_id": "2",
"nutrition_type_id": "1",
"feeding_time": "breakfast"
}
]
这是我想要实现的示例:
{
"dinner": [
{
"id": 3,
"nutrition_type_id": 2,
"nutrition_measurement_id": 1
},
{
"id": 3,
"nutrition_type_id": 1,
"nutrition_measurement_id": 2
}
],

"breakfast": [
{
"id": 3,
"nutrition_type_id": 2,
"nutrition_measurement_id": 3
},
{
"id": 5,
"nutrition_type_id": 1,
"nutrition_measurement_id": 4
}
]

}

这是我的模型:

class HorseNutrition(models.Model):
horse = models.ForeignKey(Horse, models.DO_NOTHING)
nutrition_type = models.ForeignKey('NutritionType', models.DO_NOTHING)
nutrition_measurement = models.ForeignKey('NutritionMeasurement', models.DO_NOTHING)
feeding_time = models.CharField(max_length=10, blank=True, null=True)
class Meta:
managed = False
db_table = 'horse_nutrition'

class NutritionMeasurement(models.Model):
name = models.CharField(unique=True, max_length=30, blank=True, null=True)
class Meta:
managed = False
db_table = 'nutrition_measurement'

def __str__(self):
return self.name
def __unicode__(self):
return self.name


class NutritionType(models.Model):
name = models.CharField(unique=True, max_length=30, blank=True, null=True)
class Meta:
managed = False
db_table = 'nutrition_type'

def __str__(self):
return self.name
def __unicode__(self):
return self.name

这是我的序列化器

class HorseNutritionSerializer(serializers.ModelSerializer):

nutrition_measurement_id = serializers.ReadOnlyField(source = 'nutrition_measurement.name')
nutrition_type_id = serializers.ReadOnlyField(source = 'nutrition_type.name')

class Meta:
model = HorseNutrition
fields = ['id', 'nutrition_measurement_id', 'nutrition_type_id', 'feeding_time']

这是我的观点:

class HorseNutritionView(APIView):

def get (self, request, format = None):
#id = int(request.GET.get(self.lookup_url_kwarg))
id = 1
if id != None:
queryset = HorseNutrition.objects.filter(horse_id = id)
serializer = HorseNutritionSerializer(queryset, many = True)
return Response(serializer.data)
else:
return Response(status = status.HTTP_400_BAD_REQUEST)

最佳答案

您可以使用自定义的 ListSerializer(我们将在序列化程序的 Meta 中将其设置为 list_serializer_class)并覆盖其 to_representation 并使用 itertools.groupby 对结果进行分组:

from itertools import groupby

class HorseNutritionListSerializer(serializers.ListSerializer):
def to_representation(self, data):
ret = super().to_representation(data)
return {key: list(group) for key, group in groupby(ret, key=lambda x: x['feeding_time'])}

@property
def data(self):
ret = serializers.BaseSerializer.data.fget(self)
return serializers.ReturnDict(ret, serializer=self)


class HorseNutritionSerializer(serializers.ModelSerializer):
nutrition_measurement_id = serializers.ReadOnlyField(source = 'nutrition_measurement.name')
nutrition_type_id = serializers.ReadOnlyField(source = 'nutrition_type.name')

class Meta:
model = HorseNutrition
fields = ['id', 'nutrition_measurement_id', 'nutrition_type_id', 'feeding_time']
list_serializer_class = HorseNutritionListSerializer

此外,为了正确完成此分组,您的查询集必须排序,您可以在 View 中执行此操作:

class HorseNutritionView(APIView):

def get (self, request, format = None):
#id = int(request.GET.get(self.lookup_url_kwarg))
id = 1
if id != None:
queryset = HorseNutrition.objects.filter(horse_id = id).order_by('feeding_time')
serializer = HorseNutritionSerializer(queryset, many = True)
return Response(serializer.data)
else:
return Response(status = status.HTTP_400_BAD_REQUEST)

关于django - 如何通过 Django 中的模型属性之一对对象数组进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67621228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com