python / intermediate
Snippet
Executing Asynchronous Model Persistence using Django asave Method
Django provides asynchronous model methods like asave() to allow saving model instances directly from async execution contexts without needing sync_to_async wrappers.
snippet.py
python
1
2
3
4
5
6
7
8
9
import asynciofrom myapp.models import AuditLogasync def record_log_entry(action_name: str, user_id: int):log_entry = AuditLog(action=action_name, user_id=user_id)await log_entry.asave()return log_entry.idasyncio.run(record_log_entry("USER_LOGIN", 42))
django
Breakdown
1
log_entry = AuditLog(action=action_name, user_id=user_id)
Instantiates a model object in memory without making a database call.
2
await log_entry.asave()
Asynchronously persists the record to the database non-blockingly inside the async event loop.
3
return log_entry.id
Accesses the auto-populated primary key assigned after successful async insertion.