serialize data to ArrayField(models.IntegerField(),default=list) field - json

I have the following field in postgres database :ArrayField(models.IntegerField(),default=list).
When I send data from post request I get the following error:
invalid literal for int() with base 10: '[176,68]'
while the data sent is price:[176,68]
Here is my serializer for price :
class StringArrayField(ListField):
"""
String representation of an array field.
"""
def to_representation(self, obj):
obj = super().to_representation( obj)
# convert list to string
return ",".join([(element) for element in obj])
def to_internal_value(self, data):
return super().to_internal_value( data)
class MySerializer(serializers.ModelSerializer):
price = StringArrayField()
class Meta:
model = myModel
fields =('price')

You must pass a child serializer to the listfield.
price = serializers.ListField(
child=serializers.IntegerField(min_value=0, max_value=100)
)

Related

Serializing Django FilterSet

I'm using django-filter (https://django-filter.readthedocs.io/en/stable/guide/install.html).
How can I serialize the Filterset in order to send it back to my angular Frontend?
views.py:
#api_view(['GET'])
def materialien_search(request):
filter = MaterialFilter(request.GET, queryset=Materialien.objects.all())
materialien_serializer = MaterialienSerializer(filter, many=True)
return JsonResponse(materialien_serializer.data, safe=False)
serializers.py:
class MaterialienSerializer(serializers.ModelSerializer):
class Meta:
model = Materialien
fields = [field.name for field in Materialien._meta.get_fields()]
filter.py:
class MaterialFilter(django_filters.FilterSet):
class Meta:
model = Materialien
fields = '__all__'
I'd be thankful for every help.
The Filterset should be a GET QueryDict, but all my attemps of serializing or converting it to JSON failed because Materialfilter is neither iterable nor serializable. So json.dumps and json.load and
serializers.serialize("json", filter) did not work.
TypeError: 'MaterialFilter' object is not iterable
TypeError: Object of type MaterialFilter is not JSON serializable

Convert model objects in OrderedDict to Json django

In [32]: obj
OrderedDict([('code', 'COO21'),
('name', 'sai'),
('country', <Country: INDIA>)])
Error:-
TypeError: Object of type Country is not JSON serializable
Not able to convert model objects in ordered dict to json
Override the to_representation() method in your serializer to customize the response when sending back to the view/controller.
instance is the object of the serializing model.
def to_representation(self, instance):
ret = super().to_representation(instance)
ret["country"] = instance.country.name if country else None
return ret

Get string (not dict) for SQLAlchemy JSON column

Given e.g.:
class Alarm(Base):
__tablename__ = 'alarm'
cfg = Column(JSON, nullable=False)
alarm = Alarm.query.one()
SQLAlchemy returns alarm.cfg as a dict, which is useful most of the time,
but how do I get the JSON as a str, unconverted?

Input format and Output format in Django Rest Framework Seriaizer

Hi my client api will send me char array like=>
["user1","user2","user3",...]
My model field is CharField like=>
emplist = models.CharField(max_length=1000,null=False,blank=False)
I would like to convert this array input to string in serializer and string output to array in the serializer. Can I do that?
How can I handle this array with any other way?
You can definitely handle with a couple of tweaks on your Model.
Alter your emplist field to become _emplist
_emplist = models.CharField(max_length=1000, null=False, blank=False)
Add property methods to your model for emplist
#property
def emplist(self):
return self._emplist.split(',')
#emplist.setter
def emplist(self, value):
if isinstance(value, list):
self._emplist = ','.join(value)
elif isinstance(value, str):
self._emplist = value
Now in your Serializer just add ListSerializer field to you emplist field
emplist = serializers.ListSerializer(child=serializers.CharField(allow_blank=False, allow_null=False))
And now it is going to work perfectly for this case.

django rest framework + mariaDB: custom JSONField

Django: v2.1.5
DRF: v3.9.1
mariaDB: v10.3
Hi, I am a DRF newbie and I have been struggling with json field.
DRF does not support official json field type working with mariaDB and even though there is a 3rd-party package for mysql(django-mysql) but not compatible with mariaDB.
So I searched and started implementing custom jsonfield and it looks like:
model.py:
class JSONField(models.TextField):
def to_dict(self, value):
""" convert json string to python dictionary """
return json.loads(value)
def to_json(self, value):
""" convert python dictionary to json string """
return json.dumps(value)
def from_db_value(self, value, expression, connection):
""" convert string from db to python dictionary """
if value is None:
return value
return self.to_dict(value)
def to_python(self, value):
""" convert model input value to python dictionary """
if isinstance(value, dict):
return value
if value is None:
return value
return self.to_dict(value)
def get_prep_value(self, value):
""" convert python dictionary to string before writing to db """
return self.to_json(value)
class Project(models.Model):
objects = models.Manager()
project_user = JSONField(null=True)....
serializers.py:
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('project_code'...)
def create(self, validated_data):
"""
Create and return a new `Project` instance, given the validated data.
"""
return Project.objects.create(**validated_data)
views.py:
class ListCreateProjectView(APIView):
"""
POST admin/_proj_/
: create a project
"""
def post(self, request, format=None):
serializer = ProjectSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data)
else:
return Response(data=serializer.errors)
please let me know what I am doing wrong here or a way to use 3rd party package rather than custom jsonfield
Thanks a lot and have a great day guys!
For people who suffer from this kind of problem, I actually solved this problem, but in an informal way. I set JSONfield as a textfield in DB, and handle (str->json),(json->str) in the view. But again, this is an informal way (I think) and you will need another solution than this. If you find one, please share it for me and other people :)