Django channel image serializing error says You cannot call this from an async context - use a thread or sync_to_async

У меня есть сериализатор счетов-фактур, который включает сериализатор изображений, поскольку счета-фактуры имеют отношение один ко многим с изображениями

я получил эту ошибку, когда включил many=True в поле images в сериализаторе счетов-фактур

но все работает нормально, если many=False. Мои модели:

`class Invoice(models.Model):
    class PaymentMethod(models.TextChoices):
        CASH = "CASH", _("Cash")
        CREDIT = "CREDIT", _("Credit")
        CONTRACT = "CONTRACT", _("Contract")
    tips = models.FloatField(default=0, blank=True, null=True)
    price = models.FloatField(default=0, blank=True, null=True)
    expected_price = models.FloatField(default=0, blank=True, null=True)
    passenger = models.CharField(max_length=100, blank=True, null=True)
    client = models.IntegerField(blank=True, null=True)

    payment_method = models.CharField(
        max_length=50, choices=PaymentMethod.choices)
`

`
class Image(models.Model):
    invoice = models.ForeignKey(
        "invoices.Invoice", on_delete=models.CASCADE, related_name="images")
    image = models.ImageField(upload_to=documents_path)
`

Сериализаторы:

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



`

В моем приложении есть много сериализаторов, в которых поле ссылается на другой сериализатор с many=True и работает нормально, но в этом он выдает ошибку, я искал с ошибкой, но не нашел ни одного вопроса как у меня, поэтому я надеюсь, что кто-нибудь сможет помочь

проблема была из-за того, что при получении invoice.images выполнялся новый запрос к базе данных, который является синхронизацией, поэтому я отредактировал свой менеджер счетов, чтобы предварительно получать изображения при получении любого счета

 class InvoiceManager(Manager):
    def get_queryset(self):
        return super().get_queryset().prefetch_related('images')
Вернуться на верх