gpt4 book ai didi

python - Django Rest Framework 动态分组对象

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

我的问题与 Django RestFramework 以及如何动态分组对象有关。我找到的最相似的答案来自 Rex Salisbury here但不适用于 n 个组:

模型.py

class Product(models.Model):
name = models.CharField(max_length=20)

class Ingredient(models.Model):
name = models.CharField(max_length=20)

class Mix(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
percentage = models.FloatField()

class Meta:
unique_together = ('product', 'ingredient')

serializer.py

class MixSerializer(serializer.ModelSerializer):
class Meta:
model = Mix
fields = ('product', 'liquid', 'percentage')

views.py

class MixView(viewsets.ModelViewSet):
queryset = Mix.objects.all()
serializer_class = MixSerializer

这是我目前从 API 获得的结构示例:

[ 
{
"product": "White Russian",
"ingredient": "Vodka",
"percentage": 0.54
},
{
"product": "White Russian",
"ingredient": "Coffee Liquer",
"percentage": 0.27
},
{
"product": "White Russian",
"ingredient": "Single Cream",
"percentage": 0.19
}
]

我一直在尝试以尽量减少产品名称重复的方式对这些进行分组,就像这样,

{
"product": "White Russian",
"ingredients": {
"Vodka": 0.54,
"Coffee Liquer": 0.27,
"Single Cream": 0.19
}
}

遵循 Nested Relationship 的文档但我不再相信这是正确的做法。我很乐意从对象过滤器获取这些数据,但无法与序列化程序/ View 一起实现。

最佳答案

首先请注意,根据您的示例,您是按产品分组的,因此您不是在寻找 MixView,而是在寻找 ProductView

你可以做什么:

# Serializers
class MixSerializer(serializer.ModelSerializer):
ingredient_name = serializers.CharField(source='ingredient.name')
class Meta:
model = Mix
fields = ('ingredient_name', 'percentage')

class ProductSerializer(serializer.ModelSerializer):
ingridients = MixSerializer(many=True, read_only=True)
class Meta:
model = Product
fields = ('name', 'ingridients')

# Views
class ProductView(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer

应该给你这样的东西:

{
"name": "White Russian",
"ingredients": [
{"ingredient_name": "Vodka", "percentage" : 0.54},
{"ingredient_name": "Coffee Liquer", "percentage" : 0.27},
{"ingredient_name": "Single Cream", "percentage" : 0.19}
]
}

附言要使其成为非只读的,您还需要在 ProductSerializer 下实现 createupdate 方法

关于python - Django Rest Framework 动态分组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092167/

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