question

Ryan Quey avatar image
Ryan Quey asked Erick Ramirez commented

How can I append or prepend to a Collection using Python Driver?

I asked a similar question before regarding the Java driver, but now I'm wondering about the Python driver.


For Python driver 3.24, is it possible to use the models and object mapper classes to append or prepend to a collection column (ie, a SET or a LIST), rather than overwriting it? Of course I could accomplish the same by writing out straight CQL. But is there a straightforward way to do so using the models that I have setup for my app already?

python drivercollections
1 comment
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Erick Ramirez avatar image Erick Ramirez ♦♦ commented ·

It's in the middle of the night for me (1am in Melbourne, Australia) and I'm responding on my mobile.

Let me get one of the Drivers engineers to respond. Cheers!

0 Likes 0 ·

1 Answer

smadhavan avatar image
smadhavan answered Ryan Quey commented

@Ryan Quey, you could perform something similar to below example.

For a List:

# appends the elements of the given list to the end of the column
Row.objects(row_id=5).update(list_column__append=[6, 7])

# prepends the elements of the given list to the beginning of the column
Row.objects(row_id=5).update(list_column__prepend=[1, 2])

For Set:

# adds the elements of the given set to the column
Row.objects(row_id=5).update(set_column__add={6})

# removes the elements of the given set to the column
Row.objects(row_id=5).update(set_column__remove={4})

The key to is below:

Using the syntax .update(column_name={x, y, z}) will overwrite the contents of the container, like updating a non container column. However, adding __ to the end of the keyword arg, makes the update call add or remove items from the collection, without overwriting then entire column.

See API documentation for additional reference.

1 comment Share
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Ryan Quey avatar image Ryan Quey commented ·

This is great! I wasn't sure if the python driver supports appends and prepends, since the Java driver doesn't. Thanks

0 Likes 0 ·