Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Changing a Peewee CharField to a TextField

I’m using Peewee and I have an existing database full of posts with a content field that I accidentally set to a CharField. I want to change it to a TextField but when I did, I got this error:

peewee.DataError: value too long for type character varying(255)

/cc Kenneth Love

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

That's a strange error.

My guess is that you'll need to write a schema migration.

I’ve used them to drop and add columns from my db but there isn’t a way (as far as I can tell) to keep the column name and the data in it while changing the field type

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Yeah, looking at the full documentation there isn't a change_field_type operation.

You could rename your existing field, add a new field with the correct name and type, copy the data over from old_field to new_field, and then drop old_field.

Maybe not ideal but should work?

How would you copy the data?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Well, the new field would have to be nullable for it to create correctly. So, assuming that:

  • select all the existing rows
  • perform an update on each one to write the current value of old_field into new_field
  • save each record

I'd assume you could do all of this in the one migration script. Might just need multiple calls to migrate().

Thank you!