Search code examples
postgresqlpython-3.5peeweepostgresql-9.5

Peewee update a field to the result of a function


I have a function that takes one database field and modifies it so it can become another field.

I'm trying to run this:

def get_text_words(text):
    if not text:
        return []
    else:
        # Return a list of words that make up text
        return text.split(' ')

q = Text.update(Text.words = get_text_words(Text.text))
q.execute()

When I run it, it returns an empty list. After some investigation with print statements, the function get_text_words is receiving a peewee <TextField> object rather than the text value of the field. It's not passing the if text: statement and returning an empty list as a result.

I know that I could iterate, calculate, and save, but I'd like to see if there's a possibility of running it in one query like the above so it's fast. I've already blanked out the database (no worries, it's a duplicate of production), so the query ran, just not sure how to operate on the value of the field.

Is there a way to run that type of update statement where it takes one field and puts it through a function that operates on the value and returns the result to assign to another field?


Solution

  • You don't seem to realize that the update() method results in the generation of a SQL UPDATE query. The only way your code would work is if, somehow, Peewee decompiled the Python and translated it into SQL.

    You want to apply a SQL function, so look in your database for the function...Seems like you want Postgres string_to_array since you're trying to get a list?

    So:

    q = Text.update({Text.words: fn.string_to_array(Text.text, ' ')})