Django: List field in model?

后端 未结 9 1570
感动是毒
感动是毒 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:39

    I think it will help you.

    from django.db import models
    import ast
    
    class ListField(models.TextField):
        __metaclass__ = models.SubfieldBase
        description = "Stores a python list"
    
        def __init__(self, *args, **kwargs):
            super(ListField, self).__init__(*args, **kwargs)
    
        def to_python(self, value):
            if not value:
                value = []
    
            if isinstance(value, list):
                return value
    
            return ast.literal_eval(value)
    
        def get_prep_value(self, value):
            if value is None:
                return value
    
            return unicode(value)
    
        def value_to_string(self, obj):
            value = self._get_val_from_obj(obj)
            return self.get_db_prep_value(value)
    
    class ListModel(models.Model):
        test_list = ListField()
    

    Example :

    >>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])
    
    >>> ListModel.objects.get(id=1)
    
    >>> o = ListModel.objects.get(id=1)
    >>> o.id
    1L
    >>> o.test_list
    [[1, 2, 3], [2, 3, 4, 4]]
    >>> 
    
    0 讨论(0)
  • 2020-11-29 19:39

    You can flatten the list and then store the values to a CommaSeparatedIntegerField. When you read back from the database, just group the values back into threes.

    Disclaimer: according to database normalization theory, it is better not to store collections in single fields; instead you would be encouraged to store the values in those triplets in their own fields and link them via foreign keys. In the real world, though, sometimes that is too cumbersome/slow.

    0 讨论(0)
  • 2020-11-29 19:41

    Just use a JSON field that these third-party packages provide:

    • django-jsonfield
    • django-annoying

    In this case, you don't need to care about the field value serialization - it'll happen under-the-hood.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题