cassandra.cqlengine.query - Query and filter model objects


QuerySet objects are typically obtained by calling objects() on a model class. The methods here are used to filter, order, and constrain results.

class ModelQuerySet



Returns a queryset matching all rows

for user in User.objects().all():

Set a batch object to run the query on.

Note: running a select query with a batch object will raise an exception


Sets the consistency level for the operation. See ConsistencyLevel.

for user in User.objects(id=3).consistency(CL.ONE):

Returns the number of rows matched by this query.

Note: This function executes a SELECT COUNT() and has a performance cost on large datasets


Returns the number of rows matched by this query. This function uses count() internally.

Note: This function executes a SELECT COUNT() and has a performance cost on large datasets


Returns the DISTINCT rows matched by this query.

distinct_fields default to the partition key fields if not specified.

Note: distinct_fields must be a partition key or a static column

class Automobile(Model):
    manufacturer = columns.Text(partition_key=True)
    year = columns.Integer(primary_key=True)
    model = columns.Text(primary_key=True)
    price = columns.Decimal()


# create rows


# or

(*args, **kwargs)

Adds WHERE arguments to the queryset, returning a new queryset

See Retrieving objects with filters

Returns a QuerySet filtered on the keyword arguments

(*args, **kwargs)

Returns a single instance matching this query, optionally with additional filter kwargs.

See Retrieving objects with filters

Returns a single object matching the QuerySet.

user = User.get(id=1)

If no objects are matched, a DoesNotExist exception is raised.

If more than one object is found, a MultipleObjectsReturned exception is raised.


Limits the number of results returned by Cassandra. Use 0 or None to disable.

Note that CQL’s default limit is 10,000, so all queries without a limit set explicitly will have an implicit limit of 10,000

# Fetch 100 users
for user in User.objects().limit(100):

# Fetch all users
for user in User.objects().limit(None):

Sets the number of rows that are fetched at a time.

Note that driver’s default fetch size is 5000.

for user in User.objects().fetch_size(500):

Check the existence of an object before insertion.

If the insertion isn’t applied, a LWTException is raised.


Check the existence of an object before an update or delete.

If the update or delete isn’t applied, a LWTException is raised.


Sets the column(s) to be used for ordering

Default order is ascending, prepend a ‘-’ to any column name for descending

Note: column names must be a clustering key

from uuid import uuid1,uuid4

class Comment(Model):
    photo_id = UUID(primary_key=True)
    comment_id = TimeUUID(primary_key=True, default=uuid1) # second primary key component is a clustering key
    comment = Text()


u = uuid4()
for x in range(5):
    Comment.create(photo_id=u, comment="test %d" % x)

for comment in Comment.objects(photo_id=u):
    print comment.comment_id

for comment in Comment.objects(photo_id=u).order_by("-comment_id"):
    print comment.comment_id

Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key


Load only these fields for the returned query


Don’t load these fields for the returned query


Allows for custom timestamps to be saved with the record.


Sets the ttl (in seconds) for modified data.

Note that running a select query with a ttl value will raise an exception


Performs an update on the row selected by the queryset. Include values to update in the update like so:


Passing in updates for columns which are not part of the model will raise a ValidationError.

Per column validation will be performed, but instance level validation will not (i.e., Model.validate is not called). This is sometimes referred to as a blind update.

For example:

class User(Model):
    id = Integer(primary_key=True)
    name = Text()

setup(["localhost"], "test")

u = User.create(id=1, name="jon")


# sets name to null

Also supported is blindly adding and removing elements from container columns, without loading a model instance from Cassandra.

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

Given the model below, here are the operations that can be performed on the different container columns:

class Row(Model):
    row_id      = columns.Integer(primary_key=True)
    set_column  = columns.Set(Integer)
    list_column = columns.List(Integer)
    map_column  = columns.Map(Integer, Integer)


  • add: adds the elements of the given set to the column

  • remove: removes the elements of the given set to the column

# add elements to a set

# remove elements to a set


  • append: appends the elements of the given list to the end of the column

  • prepend: prepends the elements of the given list to the beginning of the column

# append items to a list
Row.objects(row_id=5).update(list_column__append=[6, 7])

# prepend items to a list
Row.objects(row_id=5).update(list_column__prepend=[1, 2])


  • update: adds the given keys/values to the columns, creating new entries if they didn’t exist, and overwriting old ones if they did

# add items to a map
Row.objects(row_id=5).update(map_column__update={1: 2, 3: 4})

class DoesNotExist

class MultipleObjectsReturned

class LWTException

Lightweight conditional exception.

This exception will be raised when a write using an IF clause could not be applied due to existing data violating the condition. The existing data is available through the existing attribute.


existing – The current state of the data which prevented the write.