Loadding Instance of model from serializer: can help you fix over Max Length when load data

I was migrating data from SQLite to Postgresql. After dumped data from SQLite to XML file, I change database engine to Postgresql,  then I tried to load data using 'python manage.py loaddata' command, but it raise 'too long value' error. I didn't capture the actual error message...

To made it quick, I don't want to do any code change ( add max_length validation to the form ) at that time. So I would go with a workaround script that just help me to skip one that exceed limit or cut off the string because it's not very important.

Serialization seemed to be a way to go as I can load instance of a model from XML file, edit then save to Postgresql.

As it said that max_length is 240 characters, I can see that only 'short_description' field has limit at that length. So I'll just focus on 'short_description' field.

from django.core import serializers

def load():
    listing3 = open( 'sqlite_data/listing.xml')
    listing3_data = listing3.read()
   
    des= serializers.deserialize( "xml", listing3_data )
   
    for each_des in des:
        print each_des
        #check if an object has attribute name 'short_description'
        if getattr( each_dess.object , 'short_description' , ''):
        
            if len( each_des.object.short_description) > 240:
                #Cut off text if it exceeds limit
                each_des.object.short_description =                         
each_des.object.short_description[:240]
                each_des.save()
fix_max_length.py (625 bytes) , listing3.xml (3.9 KB)

You can run the function by go to working directory. Bring up a Django shell.

python manage.py shell

Then load the function we created.

from fix_max_length import load
load()

Post your comment:

Author:

  • chanita

Archives:

Powered by Django.