Pattu Pattu - 1 month ago 16
Python Question

Adding an optional non-model field via Django core serializer

I am trying to serialize a DJango queryset object.

data = Data.objects.filter(name__icontains='John')
data_list = serializers.serialize('json', data, fields=('name', 'title'))
return HttpResponse(data_list, content_type="application/json")


STDOUT of data_list

[{"pk": 4, "model": "XXX", "fields": {"name": "John ad", "title": "Mr. "}}]


In the output list I also want to add a dummy field with some hardcoded values.

STDOUT of data_list

[{"pk": 4, "model": "XXX", "fields": {"name": "John ad", "title": "Mr. ", "Dummy": "Value"}}]


Any help on how I should proceed or any links I should read would be appreciated.

Answer

One way to do this is just annotate your queryset with this dummy value. Using Value expression

from djanog.db.models import Value
data = Data.objects.filter(name__icontains='John').annotate(dummy=Value('Value'))
data_list = serializers.serialize('json', data, fields=('name', 'title', 'dummmy'))

Another way is wrap your queryset in generator:

def qs_with_dummy(queryset):
    for obj in queryset:
        obj.dummy = 'Value'
        yield obj

data = qs_with_dummy(Data.objects.filter(name__icontains='John'))
data_list = serializers.serialize('json', data, fields=('name', 'title', 'dummy')