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 database?
Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.
Field models are used to calculate the values of field functions under given boundary and loading conditions. Field functions are physical quantities which depend on their geometrical location, such as temperature (a scalar field) or velocity (a vector field).
You can convert it into string by using JSON and store it as string.
For example,
In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]) Out[3]: '[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]'
You can add a method into your class to convert it automatically for you.
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)
If you're using Django 1.9 or above, and you use postgresql, there is a new class called JSONField, you should use it instead. Here is a link to it
There is a good talk about PostgreSQL JSONs and Arrays on youtube. Watch it, it has very good information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With