如何在Django Model字段中存储Array(不使用PostgreSQL)?

时间:2022-01-06 08:00:40

What is the way to store an array in a Django Model Field?

在Django模型字段中存储数组的方法是什么?

In some cases, using a separate model/table is not performant. This is static information that not need to be indexed. I want to manage simple array in a model field.

在某些情况下,使用单独的模型/表不具备性能。这是不需要编制索引的静态信息。我想在模型字段中管理简单数组。

1 个解决方案

#1


0  

You could write your own field class - something like:

您可以编写自己的字段类 - 类似于:

import json
from django.db import models

class JSONField(models.TextField):
    description = "A field to store arbitrary python objects in JSON format"

    def from_db_value(self, value, expression, connection, context):
        if value is None or value == "":
            return None
        return json.loads(value)

    def to_python(self, value):
        if value is None:
            return value
        if not isinstance(value, basestring):
            return value
        return json.loads(value)

    def get_prep_value(self, value):
        return json.dumps(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

    def formfield(self, **kwargs):
        defaults = {'form_class': JSONFormField}
        defaults.update(kwargs)
        return super(JSONField, self).formfield(**defaults)


class JSONFormField(forms.CharField):
    widget = forms.Textarea

    def to_python(self, value):
        return json.loads(value)

    def prepare_value(self, value):
        return json.dumps(value)

    def clean(self, value):
        return self.to_python(value)

#1


0  

You could write your own field class - something like:

您可以编写自己的字段类 - 类似于:

import json
from django.db import models

class JSONField(models.TextField):
    description = "A field to store arbitrary python objects in JSON format"

    def from_db_value(self, value, expression, connection, context):
        if value is None or value == "":
            return None
        return json.loads(value)

    def to_python(self, value):
        if value is None:
            return value
        if not isinstance(value, basestring):
            return value
        return json.loads(value)

    def get_prep_value(self, value):
        return json.dumps(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

    def formfield(self, **kwargs):
        defaults = {'form_class': JSONFormField}
        defaults.update(kwargs)
        return super(JSONField, self).formfield(**defaults)


class JSONFormField(forms.CharField):
    widget = forms.Textarea

    def to_python(self, value):
        return json.loads(value)

    def prepare_value(self, value):
        return json.dumps(value)

    def clean(self, value):
        return self.to_python(value)