Asynchronous management command in django

Django -- Posted on July 25, 2023

Asynchronous management command example for django with version 4.2 and for psycopg3 

              
                import asyncio
from django.core.management.base import BaseCommand
from app.models import (
    Model1,
)

class Command(BaseCommand):

    async def import_data_async(self):
        item1, c1_created = await Model1.objects.aupdate_or_create(name="some name")
        item2, c1_created = await Model1.objects.aupdate_or_create(name="some name 2")
        await item1.related.aadd(item2)
 
    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.import_data_async())
        self.stdout.write(self.style.SUCCESS('Data import completed successfully.'))
                  
   
            

Related Posts