Hey guys it’s my first time using Django and I’m working on a with the following relationship:
User > UserWorkspace < Workspace
So every user that is created is associated with a workspace and that user can only be associated with 1 Workspace. The only person allowed to create users and workspaces is the superuser, and he has an interface to do so.
I’m working on the API for such a platform, so I need to create an endpoint that will receive the workspace_name and a list of users to create said relationship. I managed to get it working but I feel like it’s very hacky so I would like to get some input on things that I could improve.
UserSerializer
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from rest_framework.authtoken.models import Token
from trends.models.user import UserModel
class UserSerializer(serializers.ModelSerializer):
email = serializers.CharField(
validators=[
UniqueValidator(
queryset=UserModel.objects.all(),
message="userAlreadyExists",
)
],
)
password = serializers.CharField(write_only=True)
token_key = serializers.ReadOnlyField()
def create(self, validated_data):
user = UserModel.objects.create(**validated_data)
Token.objects.create(user=user)
user.set_password(validated_data["password"])
user.save()
return user
class Meta:
model = UserModel
fields = (
"id",
"email",
"first_name",
"last_name",
"role",
"password",
"token_key",
)
class UserListSerializer(UserSerializer):
workspace_role = serializers.CharField(write_only=True)
class Meta(UserSerializer.Meta):
fields = UserSerializer.Meta.fields + ("workspace_role",)
UserWorkspaceSerializer
class UserWorkspaceSerializer(serializers.ModelSerializer):
name = serializers.CharField()
users = UserListSerializer(many=True, allow_empty=False)
def create(self, validated_data):
users = []
workspace = WorkspaceModel.objects.create(name=validated_data["name"])
for user_data in validated_data["users"]:
workspace_role = user_data.pop("workspace_role")
user_serializer = UserSerializer(data=user_data)
user_serializer.is_valid(raise_exception=True)
workspace.save()
user = user_serializer.save()
user_workspace = UserWorkspaceModel.objects.create(
user=user, workspace=workspace, role=workspace_role
)
user_workspace.save()
users.append(user)
self.name = validated_data["name"]
self.users = users
return self
class Meta:
model = UserWorkspaceModel
fields = ["name", "users"]
WorkspaceView
class WorkspaceView(mixins.CreateModelMixin, viewsets.GenericViewSet):
permission_classes = [IsAuthenticated, IsAdminUser]
authentication_classes = [TokenAuthentication]
serializer_class = UserWorkspaceSerializer
def create(self, request):
serializer = UserWorkspaceSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
I don’t know if you guys also need the models I’ll skip them since this post is already very long but I can add later if you guys want.