djongo icon indicating copy to clipboard operation
djongo copied to clipboard

How to create a simple string list?

Open AntoninoBonanno opened this issue 2 years ago • 4 comments

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

  • django=4.0.4
  • django-filter=21.1
  • djangorestframework=3.13.1
  • psycopg2=2.8.6

With Pip

  • djongo==1.3.6
  • pymongo==3.12.1
  • sqlparse==0.2.4

AntoninoBonanno avatar Apr 29 '22 15:04 AntoninoBonanno

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

karthik233 avatar Jul 14 '22 03:07 karthik233

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 :')

Nuung avatar Oct 20 '22 08:10 Nuung

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

Axbry avatar Dec 04 '22 14:12 Axbry

roles = JSONField(null=True, blank=True, default=[])

That worked for me, after migrating, of course

MiltosD avatar Dec 05 '22 17:12 MiltosD