Django REST框架 - 嵌套序列化程序的查询限制?

时间:2022-07-14 19:38:23

I have a situation in which one table is related to another via a foreign key as follows:

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

models.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)

serializers.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')

This works fine, but my problem is that all the items in the container get serialized. I only want items with color='green' to be serialized.

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

2 个解决方案

#1


6  

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

#2


0  

Instead of changing how serializer works, a simplier way, its just filter you Container with green color items and them try to serialize it

而不是更改序列化程序的工作方式,简单的方法,它只是过滤容器与绿色项目,他们尝试序列化它

You can do something like this:

你可以这样做:

container_objects = Container.objects.filter(id='your_container_id',item_set__color='green')
serialized_containers = YourContainerSerializer(data=container_objects)

#1


6  

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

#2


0  

Instead of changing how serializer works, a simplier way, its just filter you Container with green color items and them try to serialize it

而不是更改序列化程序的工作方式,简单的方法,它只是过滤容器与绿色项目,他们尝试序列化它

You can do something like this:

你可以这样做:

container_objects = Container.objects.filter(id='your_container_id',item_set__color='green')
serialized_containers = YourContainerSerializer(data=container_objects)