django-ai-assistant icon indicating copy to clipboard operation
django-ai-assistant copied to clipboard

Fix: "All bulk_update() objects must have a primary key set" error in save_django_messages

Open erfani25 opened this issue 5 months ago • 4 comments

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_update on 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

  1. Use any endpoint that creates messages
  2. Send a message to the AI assistant
  3. 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:

  1. Creates messages one at a time using create()
  2. Sets message IDs immediately after creation
  3. Removes the problematic bulk_update operation
  4. 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

erfani25 avatar Jun 15 '25 10:06 erfani25