I have a Django project which has "workspaces", and users can belong to multiple workspaces, so there's a many-to-many relationship between the users and the workspaces.
Now, everything else works fine so far, but I'm having trouble adding the current user to the workspace's list of users when the user creates that workspace.
The model looks like this:
class Workspace(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(User, related_name='workspaces')
The serializer looks like this:
class WorkspaceSerializer(serializers.ModelSerializer):
class Meta:
model = Workspace
fields = ('name', 'users')
And finally, the view:
class WorkspaceViewSet(viewsets.ModelViewSet):
queryset = Workspace.objects.all().order_by('name')
serializer_class = WorkspaceSerializer
permission_classes = [permissions.IsAuthenticated,]
So, to elaborate, when a user creates a new workspace, I'd like the workspace's users
field to refer to that user. Currently, that field remains empty. How would I populate the field so that the current user is added there right on creation?
You can override the create
method of the serializer class:
class WorkspaceSerializer(serializers.ModelSerializer):
# ...
def create(self, validated_data):
instance = super(WorkspaceSerializer, self).create(validated_data)
instance.users.add(self.context['request'].user)
return instance
Note that you have access to the request in the serializer via the context
attribute. This is passed in by the corresponding view (source).