Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List field in model?

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?

like image 980
Karnivaurus Avatar asked Mar 12 '14 01:03

Karnivaurus


People also ask

Is there a list field for Django models?

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.

What are model fields?

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).


1 Answers

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.

like image 184
Ahmed Avatar answered Oct 09 '22 17:10

Ahmed