How to append to array field with bulk_update

Viewed 14

I have a ArrayField in a Peewee model backed by postgresql DB. How can I append to that field on conflict while upserting in bulk?

Model:

class User(Model):
  id = BigAutoField(primary_key=True, unique=True)
  tags = ArrayField(CharField, null=True)

SQL query I want to execute:

update user as u set tags = array_append(u.tags, val.tag) 
from (values (2, 'test'::varchar)) as val(id, tag) 
where u.id = val.id;

I've been trying for to figure out even for single insert, but facing issues in typecasting:

User.insert(user).on_conflict(
   conflict_target=[User.id],
   update={User.tags: fn.array_append(user['tag'])}
).execute()

Error I'm getting:

function array_append(unknown) does not exist
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

How do I type cast the text to varchar in peewee?

1 Answers

You can try the following:

User.insert(user).on_conflict(
   conflict_target=[User.id],
   update={User.tags: fn.array_append(user['tag'].cast('varchar'))}
).execute()
Related