简体   繁体   English

将游标传递给django-rest-framework中的Serializer?

[英]Passing a cursor to a Serializer in django-rest-framework?

I'm using Django 1.8 with django-rest-framework v3.2.2. 我正在使用Django 1.8和django-rest-framework v3.2.2。 I have a query that involves raw SQL: 我有一个涉及原始SQL的查询:

@api_view(['GET'])
def total_spending(request, format=None):
    code = request.query_params.get('code', None)
    query = 'SELECT * FROM vw_presentation_summary WHERE code=%s"
    cursor = connection.cursor()
    cursor.execute(query, tuple([code]))
    cursor.close()

My question is how to take this cursor and turn it into a data object that I can pass to django-rest-framework's Response . 我的问题是如何使用此光标并将其转换为我可以传递给django-rest-framework的Response的数据对象。

Right now I'm doing it manually, which works OK: 现在我正在手动完成它,它可以正常工作:

def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]

def total_spending(request, format=None):
    ...
    return Response(dictfetchall(cursor))

But would it be better to use a Serializer somehow? 但是以某种方式使用Serializer会更好吗? I'm not clear if Serializers do anything useful other than define the fields you want to return. 我不清楚Serializers除了定义你想要返回的字段之外还做了什么有用的事情。

Unless you're dealing with some complicated (including nested) representation of your model objects, a serializer is overkill if you're only going to use it for serializing objects. 除非您正在处理模型对象的某些复杂(包括嵌套)表示,否则如果您只是将它用于序列化对象,则序列化程序是过度的。 As you've already noticed, all of your fields can be natively serialized without any extra steps. 正如您已经注意到的那样,您的所有字段都可以本地序列化而无需任何额外步骤。

Serializers are great for shaping your output (renaming fields, grouping them with nested serializers) and doing it consistently. 序列化程序非常适合于对输出进行整形(重命名字段,使用嵌套的序列化程序对它们进行分组)并始终如一地进行。 This is especially true when working with Django models, because Django doesn't natively serialize model objects down to Python dictionaries, it prefers the actual model object. 在使用Django模型时尤其如此,因为Django本身并不将模型对象序列化为Python字典,它更喜欢实际的模型对象。

The power of a serializer comes in the deserialization, where it can map fields across models and build out relations for you. 序列化器的强大之处在于反序列化,它可以跨模型映射字段并为您构建关系。 It can also do validation across all of these relations, which is something that would usually take a while to do manually. 它还可以对所有这些关系进行验证,这通常需要一段时间才能手动执行。

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

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