for an app with three objects - User
, Event
, and Action
where users take actions on events creating an object like:
class Action(models.Model):
event = models.ForeignKey('CauseActivity', on_delete=models.CASCADE, related_name='actions')
user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='actions')
type = models.CharField(max_length=100, choices=ACTION_TYPES)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
I would like our RESTful API to be able to return the actions for one specific user, either within the user request (which requires no extra API calls) or with one additional request (get actions by user)
a simple User serializer with 'actions' as a field will return only the obj ids (response to GET ex: "actions":[108,109]
)
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
..., 'actions', )
I am aware of nesting to serialize custom fields like username = serializers.ReadOnlyField(source='user.name')
but is there a way to use serializers.ListSerializer or .ModelSerializer to serialize the full set of Action
objects' fields within my UserSerializer
? I read through https://www.django-rest-framework.org/api-guide/serializers/ and best approach isn't really clear to me. thanks