0

I have alter my model from arrayfield to json field now i am receiving error

cannot cast type character varying[] to jsonb LINE 1: ...LUMN "questionaires" TYPE jsonb USING "questionaires"::jsonb.

How to fix this ? and how it did occur?

from

questionaires   = ArrayField(models.CharField(max_length=4000), null=True, blank=True)

to

questionaires   = JSONField(null = True,blank = True)
ilja
  • 2,592
  • 2
  • 16
  • 23
  • 1
    Django can not convert the data inside your `questionaires` field from array to json. Do you have already some data inside your model/relation? If not, you could try remove the `ArrayField`, `migrate`, add the new `JSONField` and `migrate` again. – ilja May 22 '19 at 06:33

2 Answers2

3

I think you have to perform multiple stage migrates:

  1. Create temporary new field with type JSONField: Ex questionaires_2
  2. Write custom python migration RunPython to convert data manually
  3. Delete old field: questionaires
  4. Rename temporary field to the old one questionaires_2 -> questionaires

More advance: refer to this https://stackoverflow.com/a/21997589/533738

Not tested!!!

ALTER TABLE <Your Table>
ALTER COLUMN questionaires TYPE JSONB
      USING translate(questionaires::text, '{}','[]')::JSONB;
James
  • 13,571
  • 6
  • 61
  • 83
0

I had the same issue with my code while changing a field type from Array to a JSON. The job is done in 3 steps. First, you have to delete all data from related table to model; In case you using postgreSql as your database:

    DELETE FROM 'app_name'_'model_name';

Second, run the following code to delete all migrations you've done to your app from database:

    DELETE FROM django_migrations WHERE app='app_name';

Third, delete all the migrations from migrations subfolder in your app except the __init__.py file.

If it didn't work for you instead of step 1 you can run this code to delete entire table and build it from the beginning, and then do the rest:

    DROP TABLE 'app_name'_'model_name';
The Ali
  • 1
  • 2