How to clean up character database fields with leading and trailing spaces

535 views
Skip to first unread message

DJ-Tom

unread,
Nov 3, 2015, 4:57:08 AM11/3/15
to Django users
Hi,

I have several character fields with leading and trailing spaces and would like to know if it is possible to clean them up with a one-liner...

I tried the following but none of this works:


rooms.objects.all().update(name=F('name').strip()) // AttributeError: 'F' object has no attribute 'strip'

rooms.objects.all().update(name=Value(F('name')).strip())  // AttributeError: 'Value' object has no attribute 'strip'

rooms.objects.all().update(name=name.strip()) // NameError: name 'name' is not defined

Also searching via Google did not help.

Of course I could do some loop, but this seems to be not very efficient to me.

Any Idea?

Thomas

Vijay Khemlani

unread,
Nov 3, 2015, 8:02:52 AM11/3/15
to django...@googlegroups.com
As far as I know the Django ORM encapsulates SQL queries, so you can't put arbitrary python code in there (".strip()")

If I remember correctly SQL does not have a standard TRIM method, but individual database engines do, for example for Postgres


So you can run a raw SQL command or just iterate over all the rows in your data I think.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f018f0a5-3a8a-4c28-a1d6-2fb96807093e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

DJ-Tom

unread,
Nov 3, 2015, 8:37:49 AM11/3/15
to Django users
Thanks Vijay,

since this is a very small application, it uses sqlite 3 as the data backend... according to http://www.sqlite.org/lang_corefunc.html, there is a trim() function in sqlite... so I will check if this works.

best
Thomas

DJ-Tom

unread,
Nov 3, 2015, 9:31:26 AM11/3/15
to Django users

It worked! Basically it was a one-liner as well :-)


Derek

unread,
Nov 4, 2015, 11:47:27 AM11/4/15
to Django users
Reply all
Reply to author
Forward
0 new messages