如何在django中嵌套的序列化程序中过滤查询集

时间:2015-11-22 06:24:33

标签: python django django-rest-framework

我有这段代码

# Models

class NestedSample(models.Model):
    something = models.CharField(max_length=255)

class Sample(models.Model):
    thing = models.BooleanField()
    nested = models.ForeignKey(NestedSample)

# Serializers

class NestedSampleSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = api_models.NestedSample

class SampleSerializer(serializers.HyperlinkedModelSerializer):
    nested = NestedSampleSerializer() # HERE filter delete=false
    nested2 = NestedSample2Serializer() # HERE filter deletefalse

    class Meta:
        model = api_models.Sample

在我看来,我正在覆盖delete=False的查询集,但它不适用于嵌套的序列化程序。

2 个答案:

答案 0 :(得分:10)

查询集中的

delete=False仅会过滤Sample。要在嵌套序列化程序中过滤查询集,您可以使用serializers.ListSerializer,如:

class FilterDeleteListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        data = data.filter(delete=False)
        return super(FilterDeleteListSerializer, self).to_representation(data)

class NestedSampleSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = api_models.NestedSample
        list_serializer_class = FilterDeleteListSerializer 

class NestedSample2Serializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = api_models.NestedSample2
        list_serializer_class = FilterDeleteListSerializer 

class SampleSerializer(serializers.HyperlinkedModelSerializer):
    nested = NestedSampleSerializer() # HERE filter delete=false
    nested2 = NestedSample2Serializer() # HERE filter deletefalse

    class Meta:
        model = api_models.Sample

了解详情here

答案 1 :(得分:6)

我没有完全理解你的问题,但从我的想法中你已经在你的模型中有一个布尔字段,如果你删除了对象而不是实际从数据库中删除它,则设置为True( SQL DELETE)。

现在回答您的问题,如果您只想过滤嵌套的序列化程序,那么您可以使用 SerializerMethodField 。您需要指定要作为参数调用的方法,或者添加名称为' get _'的方法。后跟字段名称。在此方法中,您可以过滤查询集序列化它并返回该查询集的数据。

 class UserSerializer(serializers.ModelSerializer):
    delete_filtered_items = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_delete_filtered_items(self, obj):
        items = Item.objects.filter(user=obj,deleted=False)
        serializer = ItemsSerializer(instance=items, many=True)
        return serializer.data

上述解决方案应该适合您的要求,但如果您实施的内容类似于软删除,那么创建custom model manager似乎更清晰,更具模块性。