0

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!

1 Answers1

0

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