Django: List field in model?

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

    With my current reputation I have no ability to comment, so I choose answer referencing comments for sample code in reply by Prashant Gaur (thanks, Gaur - this was helpful!) - his sample is for python2, since python3 has no

    unicode
    method.

    The replacement below for function

    get_prep_value(self, value):
    should work with Django running with python3 (I'll use this code soon - yet not tested). Note, though, that I'm passing
    encoding='utf-8', errors='ignore'
    parameters to
    decode()
    and
    unicode() methods
    . Encoding should match your Django settings.py configuration and passing
    errors='ignore'
    is optional (and may result in silent data loss instead of exception whith misconfigured django in rare cases).

    import sys
    
    ...
    
        def get_prep_value(self, value):
            if value is None:
                return value
            if sys.version_info[0] >= 3:
                if isinstance(out_data, type(b'')):
                    return value.decode(encoding='utf-8', errors='ignore')
            else:
                if isinstance(out_data, type(b'')):
                    return unicode(value, encoding='utf-8', errors='ignore')
            return str(value)
    ...
    
    

提交回复
热议问题