Make MailboxViewSet writable: create & update
This commit is contained in:
parent
9a4f4ee17c
commit
e88e27a56e
|
@ -4,7 +4,7 @@ from orchestra.api import router, SetPasswordApiMixin, LogApiMixin
|
|||
from orchestra.contrib.accounts.api import AccountApiMixin
|
||||
|
||||
from .models import Address, Mailbox
|
||||
from .serializers import AddressSerializer, MailboxSerializer
|
||||
from .serializers import AddressSerializer, MailboxSerializer, MailboxWritableSerializer
|
||||
|
||||
|
||||
class AddressViewSet(LogApiMixin, AccountApiMixin, viewsets.ModelViewSet):
|
||||
|
@ -17,6 +17,12 @@ class MailboxViewSet(LogApiMixin, SetPasswordApiMixin, AccountApiMixin, viewsets
|
|||
queryset = Mailbox.objects.prefetch_related('addresses__domain').all()
|
||||
serializer_class = MailboxSerializer
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.request.method == 'GET':
|
||||
return self.serializer_class
|
||||
|
||||
return MailboxWritableSerializer
|
||||
|
||||
|
||||
router.register(r'mailboxes', MailboxViewSet)
|
||||
router.register(r'addresses', AddressViewSet)
|
||||
|
|
|
@ -36,6 +36,30 @@ class MailboxSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer
|
|||
postonly_fields = ('name', 'password')
|
||||
|
||||
|
||||
class MailboxWritableSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer):
|
||||
addresses = serializers.HyperlinkedRelatedField(many=True, view_name='address-detail', queryset=Address.objects.all())
|
||||
|
||||
class Meta:
|
||||
model = Mailbox
|
||||
fields = (
|
||||
'url', 'id', 'name', 'password', 'filtering', 'custom_filtering', 'addresses', 'is_active'
|
||||
)
|
||||
postonly_fields = ('name', 'password')
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
addresses = validated_data.pop('addresses', [])
|
||||
instance = super().create(validated_data)
|
||||
instance.addresses.set(addresses)
|
||||
return instance
|
||||
|
||||
@transaction.atomic
|
||||
def update(self, instance, validated_data):
|
||||
addresses = validated_data.pop('addresses', [])
|
||||
instance.addresses.set(addresses)
|
||||
return super().update(instance, validated_data)
|
||||
|
||||
|
||||
class RelatedMailboxSerializer(AccountSerializerMixin, RelatedHyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Mailbox
|
||||
|
|
Loading…
Reference in New Issue