gpt4 book ai didi

Django REST Framework - 对嵌套序列化程序的查询限制?

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

我有一种情况,其中一个表通过外键与另一个表相关,如下所示:

模型.py

class Container(models.Model):
size = models.CharField(max_length=20)
shape = models.CharField(max_length=20)

class Item(models.Model):
container = models.ForeignKey(Container, related_name='items')
name = models.CharField(max_length=20)
color = models.CharField(max_length=20)

序列化程序.py
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item


class ContainerSerializer(serializers.ModelSerializer):
items = ItemSerializer(many=True)

class Meta:
model = Container
fields = ('size', 'shape', 'items')

这工作正常,但我的问题是容器中的所有项目都被序列化。我只希望 color='green' 的项目被序列化。

最佳答案

class ContainerSerializer(serializers.ModelSerializer):
items = serializers.SerializerMethodField()

def get_items(self, obj):
query = Item.objects.filter(item_set__color='green')
serializer = ItemSerializer(query, many=True)
return serializer.data

class Meta:
model = Container
fields = ('size', 'shape', 'items')

关于Django REST Framework - 对嵌套序列化程序的查询限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25293764/

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