How to filter records based on Non-model computed fields

How to filter get_queryset() QueryResultset records based on Non-model computed fields.
I tried using the below code in the, but the get_queryset returns “” for the records that does not have computed list, instead of removing it from the QueryResultset,
Any idea what needs to be done to get this rectified and skip these records from the serializer easily?

class MyListSerializer(serializers.ModelSerializer):
class Meta:
model = models.MyList
fields = (
read_only = [‘id’,‘computed_my_list’]

def to_representation(self, instance):
    data = super(MyListSerializer, self).to_representation(instance)
    if not data.get('computed_my_list'):
        return ''
    return data

def get_computed_my_list(self,obj):
    if myList:
        return myList


Kindly let me know your view.

any pointers to this query would be helpful. Please let me know.

My gut reaction to this is that you’re trying to filter this in the wrong place. I’d think you’d be better off filtering this at the queryset - even if that means creating a filtered list from the queryset before trying to serialize it.

You could also try returning None (or not specifying any return value) instead of a null string to see what you get.

Thanks for the response and suggestion, agree on filter queryset, just wanted to check if one more pass on the Queryset can be avoided.

I had tried returning None or not specifying any return, the response comes as null instead of ’ ’ in this case and does not remove it from the list.

If it’s done as part of the query, then it’s not a second pass through the queryset - it’s preventing the database from even returning the data. Otherwise, you might be able to architect this at the view layer to add the filter at a level above the individual object serialization. (There’s not enough detail in your post about how or where that serializer is being used to offer a more specific suggestion.)

Thanks again. I could not filter with computed field as is in the get_queryset() using models.MyList.objects.filter() as the computed field is a not defined in the MyList,
it gives out this error “Cannot resolve keyword ‘computed_my_list’ into field…”.

I’d be a little surprised if your query couldn’t be modified to make that determination within the context of the query. However, you don’t specify what that computed field is, or how it’s derived, so we can’t help you determine if it’s possible to augment your query with the appropriate filter.