django-ai-assistant
django-ai-assistant copied to clipboard
Fix: "All bulk_update() objects must have a primary key set" error in save_django_messages
Bug Description
When creating messages using the save_django_messages function, an error occurs: "All bulk_update() objects must have a primary key set". This happens because the code attempts to perform a bulk_update on messages before their primary keys are properly set.
Current Behavior
- The function attempts to use
bulk_updateon newly created messages - Error occurs: "All bulk_update() objects must have a primary key set"
- Messages fail to be saved properly
Expected Behavior
- Messages should be created and saved successfully
- Message IDs should be properly set
- No errors should occur during message creation
Steps to Reproduce
- Use any endpoint that creates messages
- Send a message to the AI assistant
- Error occurs during message creation
Technical Details
The issue is in django_ai_assistant/helpers/django_messages.py in the save_django_messages function. The current implementation attempts to perform a bulk_update operation on messages that haven't yet been assigned primary keys.
Proposed Fix
@transaction.atomic
def save_django_messages(messages: list[BaseMessage], thread: "Thread") -> list["DjangoMessage"]:
from django_ai_assistant.models import Message as DjangoMessage
created_messages = []
for message in messages:
message_dict = message_to_dict(message)
created_message = DjangoMessage.objects.create(
thread=thread,
message=message_dict
)
# Set the message ID back to the LangChain message
message.id = str(created_message.id)
created_messages.append(created_message)
return created_messages
The proposed fix:
- Creates messages one at a time using
create() - Sets message IDs immediately after creation
- Removes the problematic bulk_update operation
- Maintains transactional integrity with
@transaction.atomic
While this approach may be slightly less efficient than bulk operations, it ensures reliable message creation without errors.
Environment
- django-ai-assistant version: 0.1.2
- The error affects all installations using version 0.1.2