Я пытаюсь сохранить данные в mongodb doc, но он показывает, что "требуется объект, подобный байтам, а не "str"".

try:
    print(f'user ids : {current_user_ids} type : {type(current_user_ids)}')
    print(f'user email : {current_user_emails} type : {type(current_user_emails)}')
    group_obj.user_ids = json_user_ids.encode('utf-8')
    group_obj.user_emails = json_user_emails.encode('utf-8')
    group_obj.edited_at = timezone.now()
    group_obj.save()

    refreshed_group = Groups.objects.get(group_name=group)
    print(f'refreshed group data : {refreshed_group.user_emails}')
except Exception as e:
    print(f'error occurred while saving group details : {e}')
    try:
        group_obj.user_ids = current_user_ids
        group_obj.user_emails = current_user_emails
        group_obj.save()
    except Exception as e:
        print(f'error saving group second time : {str(e)}')

группы классов(модели.Model): group_id = models.UUIDField(первичный ключ=True, редактируемый=False, по умолчанию=uuid.uuid4, уникальный=True) group_id_str = модели.Поле ввода(max_length=100, null=True, blank=True, по умолчанию="") имя_группы = модели.Поле ввода(max_length=100, null=True, blank=True) описание = модели.Поле ввода(max_length=5000, null=True, blank=True) тип = модели.CharField(max_length=100, null=True, blank=True) cid = модели.CharField(max_length=100, null=True, blank=True) идентификаторы пользователей = модели.JSONField(по умолчанию=список) user_emails = модели.JSONField(по умолчанию=список) created_at = модели.Поле даты и времени(null=True, blank=True) поле редактирования = модели.Поле даты и времени(null=True, blank=True)

{
  "_id": {
    "$oid": "67c836a30b81d0c7f42f264c"
  },
  "id": 148,
  "group_id": {
    "$binary": {
      "base64": "AHUV7hIpSWCu5mc7/gBC1w==",
      "subType": "03"
    }
  },
  "group_id_str": "007515ee-1229-4960-aee6-673bfe0042d7",
  "group_name": "group-200-1",
  "description": null,
  "type": null,
  "cid": "650d3ba581d379707a3d2fa7",
  "user_ids": "[\"622c08ae-bae4-474c-8f6d-4f5c1e981b54\", \"b857e8e5-a96f-4cac-b96a-240aaea01ee6\"]",
  "user_emails": "[\"user2710-11@gmail.com\", \"user2710-1111@gmail.com\"]",
  "created_at": {
    "$date": "2025-03-05T11:33:55.301Z"
  },
  "edited_at": {
    "$date": "2025-03-05T11:35:31.454Z"
  }
}

ошибка "a bytes-like object is required, not 'str'" скорее всего, возникает из-за того, что вы пытаетесь закодировать строковое представление JSON вместо фактических данных JSON.

исправление, которое вы можете применить здесь:

прежде чем присваивать значения group_obj.user_ids и group_obj.user_emails, десериализуйте их должным образом, используя json.loads().

import json
from django.utils import timezone

try:
    print(f'user ids : {current_user_ids} type : {type(current_user_ids)}')
    print(f'user email : {current_user_emails} type : {type(current_user_emails)}')

    # ensure we are storing lists, not JSON strings
    if isinstance(json_user_ids, str):
        json_user_ids = json.loads(json_user_ids)

    if isinstance(json_user_emails, str):
        json_user_emails = json.loads(json_user_emails)

    group_obj.user_ids = json_user_ids  # assign as a list
    group_obj.user_emails = json_user_emails  # assign as a list
    group_obj.edited_at = timezone.now()
    group_obj.save()

    refreshed_group = Groups.objects.get(group_name=group)
    print(f'refreshed group data : {refreshed_group.user_emails}')
except Exception as e:
    print(f'error occurred while saving group details : {e}')
    try:
        group_obj.user_ids = json.loads(current_user_ids) if isinstance(current_user_ids, str) else current_user_ids
        group_obj.user_emails = json.loads(current_user_emails) if isinstance(current_user_emails, str) else current_user_emails
        group_obj.save()
    except Exception as e:
        print(f'error saving group second time : {str(e)}')
Вернуться на верх