Django does not have a built-in field for arrays, but you can simulate an array using a comma-separated string, a JSON string, or a custom model field.

One way to implement a custom model field for an array is to use a Python list to store the values and a custom field to serialize and deserialize the list.

Here's an example:

import json
from django.db import models


class ArrayField(models.TextField):
    """
    A custom model field for arrays.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def from_db_value(self, value, expression, connection):
        if value is None:
            return []
        return json.loads(value)

    def to_python(self, value):
        if isinstance(value, list):
            return value
        if value is None:
            return []
        return json.loads(value)

    def get_prep_value(self, value):
        if value is None:
            return ''
        return json.dumps(value)

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

With this custom field, you can define a model field that stores an array:

class MyModel(models.Model):
    my_array = ArrayField()

You can also define getter and setter methods to manipulate the array:

class MyModel(models.Model):
    my_array = ArrayField()

    def get_my_array(self):
        return self.my_array

    def set_my_array(self, value):
        self.my_array = value

    my_array_property = property(get_my_array, set_my_array)

Now you can use the my_array_property attribute to get and set the array:

>>> instance = MyModel.objects.create(my_array=[1, 2, 3])
>>> instance.my_array_property
[1, 2, 3]
>>> instance.my_array_property = [4, 5, 6]
>>> instance.my_array
[4, 5, 6]
django getter setter model field array

原文地址: https://www.cveoy.top/t/topic/bhws 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录