doableware / djongo

Django and MongoDB database connector
https://www.djongomapper.com
GNU Affero General Public License v3.0
1.86k stars 352 forks source link

How to create a simple string list? #613

Open AntoninoBonanno opened 2 years ago

AntoninoBonanno commented 2 years ago

How is it possible to save an attribute of type Array<string> in the database?

Example, i need store this object

{
  "text": "any text",
  "roles": ["role1", "role2"]
}

I have not found any documentation about it.

NOTE: First time with django and djongo

Python script

models.py

from djongo import models
from django.contrib.postgres.fields import ArrayField

class Example(models.Model):
    id = models.CharField(max_length=24, primary_key=True) # prevent int error ???
    roles = ArrayField(models.CharField(max_length=200, blank=True))
    text = models.CharField(max_length=200, blank=False)

I try with roles = models.JSONField() without success, if I remove the roles attribute from the module the save is successful

serializers.py

from rest_framework import serializers

from AppName.models import Example

class ExampleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Example
        fields = ('roles', 'text')

views.py

from django.http.response import JsonResponse
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, permissions
from rest_framework.views import APIView

from AppName.models import Example
from AppName.serializers import ExampleSerializer

class ExampleAPI(APIView):
    permission_classes = (permissions.AllowAny,)

    # .....

    @swagger_auto_schema(request_body=ExampleSerializer, operation_summary="Create a new Example")
    def post(self, request):
        serializer = ExampleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Traceback

djongo.exceptions.SQLDecodeError: 

    Keyword: None
    Sub SQL: None
    FAILED SQL: ('INSERT INTO "AppName_example" ("id", "roles", "text") VALUES (%(0)s, %(1)s::string[], %(2)s)',)
    Params: (('', ['role'], 'asdsad'),)
    Version: 1.3.6

Env

With conda

With Pip

karthik233 commented 2 years ago

hi any updates on this? how was this solved? I also have similar issue eg: role = [10, 20]

Nuung commented 1 year ago

is there any solution? I also have similar issue!

I have to migrate to plain mongo to djongo mongo,, how to handle list[str] object :')

Axbry commented 1 year ago

If there's no dedicated solution what is the workaround?

MiltosD commented 1 year ago
roles = JSONField(null=True, blank=True, default=[])

That worked for me, after migrating, of course