简体   繁体   English

CQLEngine查询:如何返回字典?

[英]Cqlengine queries: how to return dictionary?

I'm using cqlengine in Django application, where Cassandra is the secondary database. 我在Django应用程序中使用cqlengine,其中Cassandra是辅助数据库。

In some cases I need to join manually the results of SQL and NoSQL database requests. 在某些情况下,我需要手动连接SQL和NoSQL数据库请求的结果。

For SQL I'm using: 对于SQL,我正在使用:

model_name.objects.all().values() 

to return dictionary, rather than model-instance objects. 返回字典,而不是模型实例对象。

But I can't find the appropriate methods in cqlengine . 但是我在cqlengine找不到合适的方法。

As a beginner in python, I do not know how best to implement this functionality within cqlengine library. 作为python的初学者,我不知道如何最好地在cqlengine库中实现此功能。

Maybe you have some examples of program code, providing this? 也许您有一些提供此功能的程序代码示例?

There is built-in functionality for this as of cqlengine 0.12. 从cqlengine 0.12开始,此功能具有内置功能。 This is per: CQLEngine Model Docs 这是每个: CQLEngine模型文档

As of cqlengine 0.12, we've added support for treating model instances like dictionaries. 从cqlengine 0.12开始,我们增加了对处理字典等模型实例的支持。 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即可:

dict(your_returned_model_object)

You can now access the returned objects as a dictionary, like it's referenced above. 现在,您可以像上面提到的那样,以字典的形式访问返回的对象。

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. 这将返回所有对象的字典,并且根据您的代码库,您可以进行自定义序列化和反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM