2

I'm using cqlengine in Django application, where Cassandra is the secondary database.

In some cases I need to join manually the results of SQL and NoSQL database requests.

For SQL I'm using:

model_name.objects.all().values() 

to return dictionary, rather than model-instance objects.

But I can't find the appropriate methods in cqlengine.

As a beginner in python, I do not know how best to implement this functionality within cqlengine library.

Maybe you have some examples of program code, providing this?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Maria
  • 59
  • 10

2 Answers2

2

There is built-in functionality for this as of cqlengine 0.12. This is per: CQLEngine Model Docs

As of cqlengine 0.12, we’ve added support for treating model instances like dictionaries. See below for examples.

class Person(Model):
first_name  = columns.Text()
last_name = columns.Text()

kevin = Person.create(first_name="Kevin", last_name="Deldycke")
dict(kevin)  # returns {'first_name': 'Kevin', 'last_name': 'Deldycke'}
kevin['first_name']  # returns 'Kevin'
kevin.keys()  # returns ['first_name', 'last_name']
kevin.values()  # returns ['Kevin', 'Deldycke']
kevin.items()  # returns [('first_name', 'Kevin'), ('last_name', 'Deldycke')]

kevin['first_name'] = 'KEVIN5000'  # changes the models first name

So, to answer your question... You'll want to just do a basic query, get your objects and on that, convert it to a dict:

dict(your_returned_model_object)

You can now access the returned objects as a dictionary, like it's referenced above.

mbeacom
  • 1,466
  • 15
  • 25
1

I like to use a generator for loop like such:

[dict(foo) for foo in Bar.objects.all()]

That will return a dictionary of all the objects and depending on your code base will allow you to do custom serialization and deserialization.

Ryan Kuhl
  • 90
  • 7
  • Thanks a lot! And if I need to get not all fields, but only some of them, and present the result as a dictionary? I've found how to filter fields using values_list(), but the result - is list. Is there any other way? – Maria Mar 04 '15 at 13:31
  • I wouldn't recommend using that, considering CQLEngine has it's own built in functionality to handle it... I wouldn't use values_list() either. Have you read the official documentation before using the module? – mbeacom Apr 30 '15 at 18:40