0

I'm creating an API and I need to return data in a dictionnary format sothat it can be serialized (by the API mechanism).

The code that currently works is something as simple as:

def mymethod(self):

    queryset1 = MyClass.objects.get(...) # Ccontains 1 object, easy to deal with
    queryset2 = OtherClass.objects.filter(...) # Contains N objects, hard to deal with !

    return {
        'qs1_result': queryset1.some_attribute # This works well
    }

Returning data from queryset1 is easy because there is 1 object. I just pick the attribute I need and it works. Now let's say that in addition, I want to return data from queryset2, where there are many objects, and that I don't need every attributes of the object.

How would you do that?

I repeat that I do NOT need to make the serialization myself. I just need to return structured data sothat the serialization can be made.

Thanks a lot.

David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

0

From the Django docs: https://docs.djangoproject.com/en/dev/topics/serialization/#subset-of-fields

Subset of fields If you only want a subset of fields to be serialized, you can specify a fields argument to the serializer:

from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all(), fields=('name','size'))

In this example, only the name and size attributes of each model will be serialized.

joel goldstick
  • 4,393
  • 6
  • 30
  • 46