Created
November 18, 2021 05:28
-
-
Save sortedcord/93ecaccfc03821a7e2547b09ee9a7bf5 to your computer and use it in GitHub Desktop.
List Fields in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment