ddd
ddd

Reputation: 219

Django REST framework serializing model combinations

I'm programming an online game with a JavaScript client and I use Django REST framework for the backend. I have written a quest system for it.

My quests objects are dynamically created from a django model QuestTemplate which stores information like the Quest desription and the titel (the part that is the same for every user); and another model QuestHistory where I put the information about the state of quest for a certain user: so it has fields like user and completed. They also have some nested objects: Tasks and, Rewards which are created in a similar way to the the Quest objects.

I added a pure python class Quest that combines all the fields of those models, and then I wrote a Serializer for this class. The drawback is that I have to define all the fields again in the QuestSerializer

I have seen that for the ModelSerializer you can use a inner class Meta where you specifiy the model and . Is there also a way to do this with a normal python class instead of a model (with my Quest class). http://www.django-rest-framework.org/api-guide/serializers#specifying-nested-serialization

Or:

Is it possible to specify more than one model in this inner class, so that it takes fields from my model QuestTemplate and some other fields from my model QuestHistory?

(I'm also not sure about whether this structure makes sense and asked about it here: django models and OOP design )

Upvotes: 1

Views: 391

Answers (1)

cezar
cezar

Reputation: 12032

In the class Meta of the ModelSerializer you can specify only one Model as far as I know. However there are possibilities to add custom fields to the serializer. In your case you could maybe try with:

custom_field = serializers.SerializerMethodField('some_method_in_your_serializer')

You should add the method to your serializer like this:

def some_method_in_your_serializer(self, obj):
    # here comes your logic to get fields from other models, probably some query
    return some_value # this is the value that comes into your custom_field

And add the custom_field to fields in the class Meta:

class Meta:
    fields = ('custom_field', 'all_other_fields_you_need')

Take a look in the documentation about SerializerMethodField for deeper understanding.

Upvotes: 1

Related Questions