Cqlenengine查询:如何return字典?
Cqlengine queries: how to return dictionary?
我在 Django 应用程序中使用 cqlengine,其中 Cassandra 是辅助数据库。
在某些情况下,我需要手动加入 SQL 和 NoSQL 数据库请求的结果。
对于 SQL 我正在使用:
model_name.objects.all().values()
到 return 字典,而不是模型实例对象。
但是我在cqlengine
中找不到合适的方法。
作为 python 的初学者,我不知道如何在 cqlengine
库中最好地实现此功能。
也许你有一些程序代码的例子,提供这个?
从 cqlengine 0.12 开始有内置功能。这是根据: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
所以,为了回答您的问题...您只需执行一个基本查询,获取您的对象,然后将其转换为字典:
dict(your_returned_model_object)
您现在可以像上面引用的那样访问作为字典的返回对象。
我喜欢像这样使用循环生成器:
[dict(foo) for foo in Bar.objects.all()]
这将 return 所有对象的字典,并且根据您的代码库将允许您进行自定义序列化和反序列化。
我在 Django 应用程序中使用 cqlengine,其中 Cassandra 是辅助数据库。
在某些情况下,我需要手动加入 SQL 和 NoSQL 数据库请求的结果。
对于 SQL 我正在使用:
model_name.objects.all().values()
到 return 字典,而不是模型实例对象。
但是我在cqlengine
中找不到合适的方法。
作为 python 的初学者,我不知道如何在 cqlengine
库中最好地实现此功能。
也许你有一些程序代码的例子,提供这个?
从 cqlengine 0.12 开始有内置功能。这是根据: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
所以,为了回答您的问题...您只需执行一个基本查询,获取您的对象,然后将其转换为字典:
dict(your_returned_model_object)
您现在可以像上面引用的那样访问作为字典的返回对象。
我喜欢像这样使用循环生成器:
[dict(foo) for foo in Bar.objects.all()]
这将 return 所有对象的字典,并且根据您的代码库将允许您进行自定义序列化和反序列化。