serializer adds unnnecesary fields in Javascript

Omar Gonzales

I need to generate a very clean structure of an JS Array from Django Queryset. For this I'm using a serializer.

However, they final array has extra field that may be causing problems with Google Analytics requested format.

Google Analytics resquested format:

Notice the structure of the products Array

<script>
// Send transaction data with a pageview if available
// when the page loads. Otherwise, use an event when the transaction
// data becomes available.
dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': 'T12345',                         // Transaction ID. Required for purchases and refunds.
        'affiliation': 'Online Store',
        'revenue': '35.43',                     // Total transaction value (incl. tax and shipping)
        'tax':'4.90',
        'shipping': '5.99',
        'coupon': 'SUMMER_SALE'
      },
      'products': [{                            // List of productFieldObjects.
        'name': 'Triblend Android T-Shirt',     // Name or ID is required.
        'id': '12345',
        'price': '15.25',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Gray',
        'quantity': 1,
        'coupon': ''                            // Optional fields may be omitted or set to empty string.
       },
       {
        'name': 'Donut Friday Scented T-Shirt',
        'id': '67890',
        'price': '33.75',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Black',
        'quantity': 1
       }]
    }
  }
});
</script>

dataLayer product array produced by serializer:

enter image description here

View that contains the serializer:

def thanks_deposit_payment(request):
    order_number = Order.objects.latest('id').id

    total = Order.objects.latest('id').total

    costo_despacho = Order.objects.latest('id').shipping_cost

    order_items = OrderItem.objects.filter(order=Order.objects.latest('id'))


    order_items = serialize('json', order_items, fields=['id', 'sku', 'name', 'price', 'size', 'quantity'])


    response = render(request, 'thanks_deposit_payment.html', dict(order_number=order_number, total=total,
                                                                   order_items=order_items, costo_despacho=costo_despacho))
    return response

dataLayer in template:

This is the line that produces the Products Array that is what needs to be changed:

 products: JSON.parse('{{ order_items | safe }}')

Complete JS code in template:

{% block data_layer %}

<script>
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        event: 'eec.purchase',
        ecommerce: {
            currencyCode: 'PEN',
            purchase: {
                actionField: {
                    id: {{ order_number }},
                    affiliation: 'Stickers Gallito E-Commerce',
                    revenue: {{ total }},
                    shipping: {{ costo_despacho }},
                    coupon: ''
                },
                products: JSON.parse('{{ order_items | safe }}')
            },

        }
    });
</script>

{% endblock %}

How can I match the expected format by Google?

janos

You have not specified what is serializer, but I presume it comes from from django.core import serializers. As per the documentation, indeed it maps a list of objects to this kind of layout:

[
    {
        "pk": "4b678b301dfd8a4e0dad910de3ae245b",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2013-01-16T08:16:59.844Z",
            ...
        }
    }
]

I don't see a way to customize the behavior of the serializer, but you can always re-serialize yourself manually. For example, using the json package, you can do like this:

# at the top of the script
import json

# ...

def thanks_deposit_payment(request):    
    # ...

    order_items_serialized = serialize('json', order_items, fields=['id', 'sku', 'name', 'price', 'size', 'quantity'])

    # convert the serialized string to a Python object
    order_items_obj = json.loads(order_items_serialized)

    # define the target mapping
    def mapper(p):
        return {
            'id': p['pk'],
            'sku': p['fields']['sku'],
            'name': p['fields']['name'],
            # ... and so on ...
        }

    # re-map and re-serialize the items
    order_items = json.dumps(list(map(mapper, order_items_obj)))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Make Jackson serializer override specific ignored fields

Jackson - custom serializer that overrides only specific fields

Custom Gson serializer with fields that are unknown at runtime

Custom Jackson serializer on specific fields

How to dynamically remove fields from serializer output

Django serializer inherit and extend fields

Changing serializer fields on the fly

Additional Serializer Fields in Django REST Framework 3

Django's GeoJSON serializer not serializing all fields?

Rename response fields django rest framework serializer

DRF serializer depth makes fields ignored on create

Need help understanding many and source fields in a serializer

Serializer returns object instead fields

Deserialize POST request with subset of serializer fields in DRF

Django Serializer not showing related fields

How to Dynamically set the fields of the Serializer (not during initialization)?

How to add link fields to serializer dynamically

adding additional fields to serializer from another model

JavaScript onClick adds form fields with drop down I need populated with PHP MySQL query

Can we make either of the serializer fields compulsory in the serializer class itself?

Filebeat adds unwanted blank fields

Django Rest Framework - serializer fields for only deserialization

Omitting fields during serialization for specific Gson serializer

How to connect fields in the Serializer (DjangoRestFramework)?

what is defference between django rest framwork's 'serializer' and 'serializer fields'

How to mutate validators of fields in model serializer

DRF serializer return nullable fields

how to customize fields in nested serializer?

Django DRF filtering fields in serializer

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive