Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ArrayField null=True migration with Postgresql

So in Django docs for creating new fields on Postgresql it says (Full description):

... it’s recommended you always create new columns with null=True, as this way they will be added immediately.

What if I want to create an ArrayField, something like this:

tags = ArrayField(models.CharField(max_length=255, blank=True, default=''), default=list, null=True)

Should I also pass null=True into CharField which is inside this ArrayField?

like image 761
primoz Avatar asked Apr 14 '16 08:04

primoz


2 Answers

If u are adding the null=True only because documentation says:

... it’s recommended you always create new columns with null=True, as this way they will be added immediately.

I don't think that would be necessary here in the ArrayField. Because you have already added a default value to your field. So any entry which is already present in database will have this default value(which is empty list in this case).

null=True is added so that, in case you don't specify a default value, the field value can be set to null, and you don't have enter a default value manually during migration.

In future if u don't plan to enter null values to this field, then you can omit the null=True part.

Let us say you have a table with following data:

 id | user_id 
----+---------
  1 | 66
  2 | 105
  3 | 110
  4 | 174

After adding default=list and doing migrations, your data would be something like this. Note that you don't need to specify null=True in this case.

 id | user_id | tag 
----+---------+-----
  1 | 66      | {}
  2 | 105     | {}
  3 | 110     | {}
  4 | 174     | {}

In case, you don't specify a default value and set null=True, you data would be:

 id | user_id | tag 
----+---------+-----
  1 | 66      | 
  2 | 105     | 
  3 | 110     | 
  4 | 174     | 
like image 194
ezvine Avatar answered Nov 03 '22 06:11

ezvine


I do not think setting null=True on the inner type gives you any benefit. The note in the docs you refer to only applies to the column itself, so as long as the ArrayField is nullable, the database will not have to perform a full table rewrite.

If you allow the inner type to be null, you'll have to deal with that in your code, which might not be exactly what you want.

like image 37
koniiiik Avatar answered Nov 03 '22 05:11

koniiiik