How to add list fields in a Python Django model?

Sometimes, we want to add list fields in a Python Django model.

In this article, we’ll look at how to add list fields in a Python Django model.

How to add list fields in a Python Django model?

To add list fields in a Python Django model, we can create a char field that stores the list data as a string.

For instance, we write

import json


class Foobar(models.Model):
    foo = models.CharField(max_length=200)

    def set_foo(self, x):
        self.foo = json.dumps(x)

    def get_foo(self):
        return json.loads(self.foo)

to create the Foobar model that has the foo char field.

We add the set_foo setter method to set the value of foo.

And we add the get_foo method to return the value of foo.

Conclusion

To add list fields in a Python Django model, we can create a char field that stores the list data as a string.