Reputation: 1084
The below link specifies how to create a list-field in Django.
How to create list field in django
My question; how to add, remove items to this field? if in case that's possible. I want to be able to add to and remove from this field of a Model's instance afterwards. If not possible please someone suggest me an alternative.
Upvotes: 2
Views: 2969
Reputation: 6414
in ListField
:
to_python
function is used to convert database string to python object(here is list)
get_prep_value
is used to handle python object to string(to store into database next step).
when you call your obj.listfield, such as a.list
, you'll get a python list, so you could use a.list.append(val)
, a.list.insert(0, val)
method to operate, and at last call a.save()
, listfield
will do the conversion for you between database and python.
class Dummy(models.Model):
mylist = ListField()
def insert_to_mylist(self, index, value):
self.mylist.insert(index, value)
#self.save()
def remove_from_mylist(self, value):
self.mylist.remove(value)
#self.save()
for example:
d = Dummy()
d.mylist.insert(0, 'tu')
d.save()
d.mylist.remove('tu')
d.save()
d.insert_to_mylist(0, "tu")
d.save()
d.remove_from_mylist('tu')
d.save()
if you want to insert or remove without .save()
, just add .save()
to insert_to_mylist
and remove_from_mylist
function.
ListField
is just used to conversion between database and python, so add a remove or insert to it may be difficult. But you can do it in your Model, if many Models need to use this method, just write an abstract model
.
Upvotes: 4
Reputation: 11070
My way of storing lists in models is by converting them to a string and storing them as TextField.
Upvotes: 1