accounts: role create and list apis add
This commit is contained in:
26
core/apps/accounts/serializers/role/create.py
Normal file
26
core/apps/accounts/serializers/role/create.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# django
|
||||
from django.db import transaction
|
||||
|
||||
# rest framework
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
# accounts
|
||||
from core.apps.accounts.models import Role
|
||||
|
||||
|
||||
class CreateRoleSerializer(serializers.Serializer):
|
||||
name = serializers.CharField()
|
||||
comment = serializers.CharField(required=False)
|
||||
|
||||
def validate(self, data):
|
||||
if Role.objects.filter(name=data['name']).exists():
|
||||
raise serializers.ValidationError({"name": "Role with this name already exists"})
|
||||
return data
|
||||
|
||||
def create(self, validated_data):
|
||||
with transaction.atomic():
|
||||
return Role.objects.create(
|
||||
name=validated_data.get('name'),
|
||||
comment=validated_data.get('comment'),
|
||||
)
|
||||
18
core/apps/accounts/serializers/role/list.py
Normal file
18
core/apps/accounts/serializers/role/list.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# rest framework
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
# accounts
|
||||
from core.apps.accounts.models import Role
|
||||
|
||||
|
||||
class ListRoleSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Role
|
||||
fields = [
|
||||
'id',
|
||||
'name',
|
||||
'comment',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
]
|
||||
26
core/apps/accounts/serializers/role/update.py
Normal file
26
core/apps/accounts/serializers/role/update.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# django
|
||||
from django.db import transaction
|
||||
|
||||
# rest framework
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
# accounts
|
||||
from core.apps.accounts.models import Role
|
||||
|
||||
|
||||
class UpdateRoleSerializer(serializers.Serializer):
|
||||
name = serializers.CharField()
|
||||
comment = serializers.CharField()
|
||||
|
||||
def validate(self, data):
|
||||
if Role.objects.filter(name=data['name']).exists():
|
||||
raise serializers.ValidationError({"name": "Role with this name already exists"})
|
||||
return data
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
with transaction.atomic():
|
||||
instance.name = validated_data.get('name', instance.name)
|
||||
instance.comment = validated_data.get('comment', instance.comment)
|
||||
instance.save()
|
||||
return instance
|
||||
Reference in New Issue
Block a user