0

I'm using Python 3.7 and Django. I have a view that returns the following

# Ajax request that returns articles with similar words in the titles
def get_hints(request):
    ...
    s = ArticlesService()
    objects = s.get_hints(article)
    data = serializers.serialize('json', objects)
    return HttpResponse(data, content_type="application/json")

The "get_hints" method returns an array of model objects. The thing is, on the Javascript side, the JSON is returned like so ...

[{model: "mydb.article", pk: 60945, fields: { title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" },
    ...]

Is there a way to have the JSON returned without the "model" and "fields" and just have the object's attribute returned as more traditional JSON, e.g.

{ title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }

?

Dave
  • 15,639
  • 133
  • 442
  • 830
  • Yes, use another serializer, the Django provided one is intended for exporting and loading data in the database. The django-rest-framework has the serializer you want. – dirkgroten Aug 30 '19 at 15:37
  • Possible duplicate of [django: control json serialization](https://stackoverflow.com/questions/5129794/django-control-json-serialization) – dirkgroten Aug 30 '19 at 15:45
  • @dirkgroten, In the answer you listed, they are building the JSON from scratch, one attribute at a time. If that's the only way to do it, so be it, but I was hoping there was something I coudl pass an object into taht woudl do all the hard work for me. – Dave Aug 30 '19 at 16:24
  • 1
    Then refer to my first comment. User the ModelSerializer from DRF. – dirkgroten Aug 30 '19 at 16:25
  • that something is called a serializer. Either find a Django package that has serialisers that are easy to configure and flexible (DRF has that) or write your own serializer class. The answer of Abdul below is a good start to build a simple serializer that'll serialise all your model's fields. – dirkgroten Aug 30 '19 at 16:38

1 Answers1

1

Yes. The get_dump_object method of the Serializer class is responsible for the below format

{
    "pk": "pk_val",
    "model": "model_name",
    "fields": {
        "model_field": "model_field_value",
        ...
    }
}

Following is the current implementation of the get_dump_object method.

def get_dump_object(self, obj):
    data = OrderedDict([('model', str(obj._meta))])
    if not self.use_natural_primary_keys or not hasattr(obj, 'natural_key'):
        data["pk"] = self._value_from_field(obj, obj._meta.pk)
    data['fields'] = self._current
    return data

Since you don't want the pk and model fields you can create your own serialzer class and override get_dump_object method.

from django.core.serializers.json import Serializer as JSONSerializer

class MyCustomSerializer(JSONSerializer):
    def get_dump_object(self, obj):
        return self._current

and then you can get the data in the following format

[{ title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }, ....]

by calling its serialize method.

data = MyCustomSerializer().serialize(objects)
return HttpResponse(data, content_type="application/json")
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • I don't mind having the pk, its just I'd like the object to be represented as a single JSON entity as opposed to the way it is now. Do I still need to write a custom function to dump that data? – Dave Aug 30 '19 at 15:56
  • If you want "pk" then instead of returning `self._current` you can do `data = super().get_dump_object(obj); return {'pk': data['pk'], **data['fields']}` – dirkgroten Aug 30 '19 at 16:31
  • Where am I writing that? In the custom function you have? – Dave Aug 30 '19 at 17:13