2

I am trying to create an API to return some JSON responses with Django. The app is just doing some CRUD operations and integration with Shopify API. From my understanding, I know that I can use Django Rest Framework (DRF), plain Django serializer, or return JSON response on my own.

From this thread, I know that DRF can give me a better JSON format than Django serializer.

However, is it simpler to just loop the Model and return the JSON Response on my own? For example,

for product in products:
    if 'node' in product:
        returnProduct = {}
        node = product['node']
        returnProduct['id'] = node['id'][22:]
        returnProduct['updated_at'] = node['updatedAt'].split('T', 1)[0]
        returnProduct['title'] = node['title']
        returnProduct['short_title'] = node['title'][0:48] + "..." if len(node['title']) > 48 else node['title']
        returnProducts.append(returnProduct)

data = { "products" : returnProducts}

return JsonResponse(data)

Is it because it's faster to use serializers than looping on my own? Or am I mixing up different scenarios?

Benny Chan
  • 730
  • 1
  • 8
  • 24
  • The standard JSON serializer can not serialize `DateTime` objects, etc. This is basically what the Django serialzier brings to the table. – Willem Van Onsem Oct 09 '20 at 10:41
  • If I use a for loop to loop through each object, I can format the dateTime object to string easily – Benny Chan Oct 09 '20 at 10:48
  • 1
    *can* yes, but it makes the view more *complicated* and is a against the *S* of the *SOLID* principles to "flake logic in several places". – Willem Van Onsem Oct 09 '20 at 10:52

0 Answers0