django通道映像序列化错误说你不能从异步上下文调用这个-使用线程或sync_to_async

5gfr0r5j  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(196)

我有一个发票序列化,其中包括一个图像序列化作为发票有关系一对多的图像
当我在发票序列化程序的图像字段中启用many=True时,出现此错误

Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
Traceback (most recent call last):
  File "D:\projects\TaxiTR\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 62, in __call__
    return await application(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\security\websocket.py", line 37, in __call__
    return await self.application(scope, receive, send)
  File "D:\projects\TaxiTR\core\middleware.py", line 57, in __call__
    return await super().__call__(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__
    return await self.inner(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 47, in __call__
    return await self.inner(dict(scope, cookies=cookies), receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\sessions.py", line 263, in __call__
    return await self.inner(wrapper.scope, receive, wrapper.send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\auth.py", line 185, in __call__
    return await super().__call__(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\middleware.py", line 24, in __call__
    return await self.inner(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\routing.py", line 116, in __call__
    return await application(
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 94, in app
    return await consumer(scope, receive, send)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 58, in __call__
    await await_many_dispatch(
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch
    await dispatch(result)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\consumer.py", line 73, in dispatch
    await handler(message)
  File "D:\projects\TaxiTR\env\lib\site-packages\channels\generic\websocket.py", line 173, in websocket_connect
    await self.connect()
  File "D:\projects\TaxiTR\ride\consumers.py", line 62, in connect
    shift = await self.get_active_shift()
  File "D:\projects\TaxiTR\ride\consumers.py", line 179, in get_active_shift
    shift_data = ShiftDetailSerializer(shift).data
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 555, in data
    ret = super().data
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 253, in data
    self._data = self.to_representation(self.instance)
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 686, in to_representation
    return [
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 687, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "D:\projects\TaxiTR\env\lib\site-packages\rest_framework\relations.py", line 542, in to_representation
    return [
  File "D:\projects\TaxiTR\env\lib\site-packages\django\db\models\query.py", line 394, in __iter__
    self._fetch_all()
  File "D:\projects\TaxiTR\env\lib\site-packages\django\db\models\query.py", line 1866, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "D:\projects\TaxiTR\env\lib\site-packages\django\db\models\query.py", line 87, in __iter__
    results = compiler.execute_sql(
  File "D:\projects\TaxiTR\env\lib\site-packages\django\db\models\sql\compiler.py", line 1393, in execute_sql
    cursor = self.connection.cursor()
  File "D:\projects\TaxiTR\env\lib\site-packages\django\utils\asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

但如果有很多=False,则可以正常工作****我的模型:

第一次

序列化程序:

`class ImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(required=False)

    class Meta:
        model = Image
        fields = ['image']

class InvoiceSerializer(serializers.ModelSerializer):
    total_earnings = serializers.ReadOnlyField()
    net = serializers.ReadOnlyField()
    qst = serializers.ReadOnlyField()
    gst = serializers.ReadOnlyField()
    revendence = serializers.ReadOnlyField()
    images = ImageSerializer(many=True, required=False)

    class Meta:
        model = Invoice
        fields = [
            "tips",
            "price",
            "passenger",
            "client",
            "total_earnings",
            "net",
            "qst",
            "gst",
            "revendence",
            "images",
            "id",
        ]
        read_only_fields = ['id', ]

  def create(self, validated_data):
        images_data = self.context.get('request').FILES.getlist('images', None)
        validated_data.pop('images', None)

        invoice = Invoice.objects.create(**validated_data)
        for image in images_data:
            Image.objects.create(image=image, invoice=invoice)
        return invoice

    def update(self, instance, validated_data):
        images_data = self.context.get('request').FILES.getlist('images', None)
        if images_data:

            instance.images.all().delete()
            invoice_docs = [
                Image(invoice=instance, image=image) for image in images_data
            ]
            Image.objects.bulk_create(
                invoice_docs
            )
        return super().update(instance, validated_data)


`

在我的应用程序中,我有许多串行化器,有一个字段引用另一个串行化器,许多=True,工作正常,但在这个应用程序中,它给我这个错误,我搜索了错误,但没有找到任何像我这样的问题,所以我希望有人可以帮助

2g32fytz

2g32fytz1#

问题是因为当访问发票。图像运行一个新的数据库查询,这是一个同步,所以我编辑了我的发票管理器,以预取图像时,获取任何发票

class InvoiceManager(Manager):
    def get_queryset(self):
        return super().get_queryset().prefetch_related('images')

相关问题