Faith Baghan
Faith Baghan

Reputation: 91

How to serialize a list of non model/queryset objects

I am looking for a proper way to be able to pass a manually created list of objects to Wagtail API.

The list is coming from an imported function which simply generates the following list.

List (not a queryset or model instance)

data = [ {"id":"1","name":"John"}, {"id":"2","name":"Jack"}, {"id":"3","name":"Jim"} ]

I might have done it wrong but I have added a simple property of no type in the model:

from external_source import generate_data


class MyModel(BaseContentPage):
  ...
  data = generate_data()

  ...
  api_fields = (
    ...
    + [
      APIField(data)
    ]
  )

Upvotes: 1

Views: 197

Answers (2)

Manny
Manny

Reputation: 715

It would be nice to include the error messages you get. But my first guess, based off the code you shared, is missing quotes. Refactor your code like below and you are good to go:

class MyModel(BaseContentPage):
  ...
  data = generate_data()

  ...
  api_fields = (
    ...
    + [
      APIField("data")
    ]
  )

Upvotes: 0

sibtain
sibtain

Reputation: 71

Create SerializerMethodField in your Serializer Class:

some_list = serializers.SerializerMethodField()

and then create a function get_some_list(self):

def get_some_list(self):
      data = #some code or logic
       return data

Upvotes: 0

Related Questions