简体   繁体   中英

Passing a cursor to a Serializer in django-rest-framework?

I'm using Django 1.8 with django-rest-framework v3.2.2. I have a query that involves raw 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 .

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? I'm not clear if Serializers do anything useful other than define the fields you want to return.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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