Django: List field in model?

后端 未结 9 1587
感动是毒
感动是毒 2020-11-29 18:38

In my model, I want a field that has a list of triplets. e.g. [[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the da

9条回答
  •  时光说笑
    2020-11-29 19:31

    It's quite an old topic, but since it is returned when searching for "django list field" I'll share the custom django list field code I modified to work with Python 3 and Django 2. It supports the admin interface now and not uses eval (which is a huge security breach in Prashant Gaur's code).

    from django.db import models
    from typing import Iterable
    
    class ListField(models.TextField):
        """
        A custom Django field to represent lists as comma separated strings
        """
    
        def __init__(self, *args, **kwargs):
            self.token = kwargs.pop('token', ',')
            super().__init__(*args, **kwargs)
    
        def deconstruct(self):
            name, path, args, kwargs = super().deconstruct()
            kwargs['token'] = self.token
            return name, path, args, kwargs
    
        def to_python(self, value):
    
            class SubList(list):
                def __init__(self, token, *args):
                    self.token = token
                    super().__init__(*args)
    
                def __str__(self):
                    return self.token.join(self)
    
            if isinstance(value, list):
                return value
            if value is None:
                return SubList(self.token)
            return SubList(self.token, value.split(self.token))
    
        def from_db_value(self, value, expression, connection):
            return self.to_python(value)
    
        def get_prep_value(self, value):
            if not value:
                return
            assert(isinstance(value, Iterable))
            return self.token.join(value)
    
        def value_to_string(self, obj):
            value = self.value_from_object(obj)
            return self.get_prep_value(value)
    

提交回复
热议问题