From 03666d8ed09aeaaa90cda8d7e9e8918e57049897 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Thu, 14 Oct 2021 13:03:08 +0200 Subject: [PATCH] Filter related addresses by account --- orchestra/contrib/mailboxes/serializers.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/orchestra/contrib/mailboxes/serializers.py b/orchestra/contrib/mailboxes/serializers.py index ad14b11c..1608a6ce 100644 --- a/orchestra/contrib/mailboxes/serializers.py +++ b/orchestra/contrib/mailboxes/serializers.py @@ -36,8 +36,15 @@ class MailboxSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer postonly_fields = ('name', 'password') +class AddressRelatedField(serializers.HyperlinkedRelatedField): + # Filter addresses by account (user) + def get_queryset(self): + qs = super().get_queryset() + return qs.filter(account=self.context['account']) + + class MailboxWritableSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer): - addresses = serializers.HyperlinkedRelatedField(many=True, view_name='address-detail', queryset=Address.objects.all()) + addresses = AddressRelatedField(many=True, view_name='address-detail', queryset=Address.objects.all()) class Meta: model = Mailbox @@ -46,6 +53,10 @@ class MailboxWritableSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSe ) postonly_fields = ('name', 'password') + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields['addresses'].context['account'] = self.account + @transaction.atomic def create(self, validated_data): addresses = validated_data.pop('addresses', [])