Override create to handle channel profile membership
(self, request, *args, **kwargs)
| 806 | ordering = ["-channel_number"] |
| 807 | |
| 808 | def create(self, request, *args, **kwargs): |
| 809 | """Override create to handle channel profile membership""" |
| 810 | serializer = self.get_serializer(data=request.data) |
| 811 | serializer.is_valid(raise_exception=True) |
| 812 | |
| 813 | with transaction.atomic(): |
| 814 | channel = serializer.save() |
| 815 | |
| 816 | # Handle channel profile membership |
| 817 | # Semantics: |
| 818 | # - Omitted (None): add to ALL profiles (backward compatible default) |
| 819 | # - Empty array []: add to NO profiles |
| 820 | # - Sentinel [0] or 0: add to ALL profiles (explicit) |
| 821 | # - [1,2,...]: add to specified profile IDs only |
| 822 | channel_profile_ids = request.data.get("channel_profile_ids") |
| 823 | if channel_profile_ids is not None: |
| 824 | # Normalize single ID to array |
| 825 | if not isinstance(channel_profile_ids, list): |
| 826 | channel_profile_ids = [channel_profile_ids] |
| 827 | |
| 828 | # Determine action based on semantics |
| 829 | if channel_profile_ids is None: |
| 830 | # Omitted -> add to all profiles (backward compatible) |
| 831 | profiles = ChannelProfile.objects.all() |
| 832 | ChannelProfileMembership.objects.bulk_create([ |
| 833 | ChannelProfileMembership(channel_profile=profile, channel=channel, enabled=True) |
| 834 | for profile in profiles |
| 835 | ]) |
| 836 | elif isinstance(channel_profile_ids, list) and len(channel_profile_ids) == 0: |
| 837 | # Empty array -> add to no profiles |
| 838 | pass |
| 839 | elif isinstance(channel_profile_ids, list) and 0 in channel_profile_ids: |
| 840 | # Sentinel 0 -> add to all profiles (explicit) |
| 841 | profiles = ChannelProfile.objects.all() |
| 842 | ChannelProfileMembership.objects.bulk_create([ |
| 843 | ChannelProfileMembership(channel_profile=profile, channel=channel, enabled=True) |
| 844 | for profile in profiles |
| 845 | ]) |
| 846 | else: |
| 847 | # Specific profile IDs |
| 848 | try: |
| 849 | channel_profiles = ChannelProfile.objects.filter(id__in=channel_profile_ids) |
| 850 | if len(channel_profiles) != len(channel_profile_ids): |
| 851 | missing_ids = set(channel_profile_ids) - set(channel_profiles.values_list('id', flat=True)) |
| 852 | return Response( |
| 853 | {"error": f"Channel profiles with IDs {list(missing_ids)} not found"}, |
| 854 | status=status.HTTP_400_BAD_REQUEST, |
| 855 | ) |
| 856 | |
| 857 | ChannelProfileMembership.objects.bulk_create([ |
| 858 | ChannelProfileMembership( |
| 859 | channel_profile=profile, |
| 860 | channel=channel, |
| 861 | enabled=True |
| 862 | ) |
| 863 | for profile in channel_profiles |
| 864 | ]) |
| 865 | except Exception as e: |
nothing calls this directly
no test coverage detected