Async view with serializer Django 3.1

Viewed 466

I'm trying to create an async view to solve an endpoint with Django 3.1.

I have my AsyncView and within this view I have the next code lines :

try:
    db_result= await sync_to_async(list)(Plan.objects.filter())
    serializer =  MySerializer(db_results, many=True)
    return serializer.data
except Exception:
    # Handle Exception Code

Within my serializer I have a custom field. Its data is retrieved doing other queries to the Database using its obj property. This is where I am having some problems since this is an async context.

Serializer Code:

MySerializer(serializers.ModelSerializer):

    custom_field = serializers.SerializerMethodField(required=False)

    def get_custom_field(self, obj):
        try:
            # This is failing, is not retrieving data from DB since it's async context
            related_stuff = obj.related_stuff.filter(filter_condition=filter_condition)
            # More code after this
            .
            .
            .
            .
            return custom_field_object
        except Exception:
            return None

I've tried to put an await before the Serializer in my View Code and add async property to get_custom_field method (with the sync_to_async operator in the db query). Got nothing.

Anyone know how to solve this specific problem?

0 Answers
Related