diff --git a/Sistemas/serializers.py b/Sistemas/serializers.py index 59ec2aa..56762a3 100644 --- a/Sistemas/serializers.py +++ b/Sistemas/serializers.py @@ -2,6 +2,7 @@ from rest_framework import serializers from .models import Device, Sistema, sistemas_por_cliente from Clientes.models import Clientes +from django.db.models import Q class SistemaPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def to_internal_value(self,data): @@ -33,8 +34,22 @@ class DeviceSerializer(serializers.ModelSerializer): #the request context passed throught argument in the view to the serializer #given that the macAddres field are read_Only in the beggining of this serialazer #we need passing the post data to the creation instance before commited to the DB - def create(self, validated_data): - validated_data['macAddress']= self.context['request'].data.get('macAddress') + def create(self, validated_data): + mac_address = self.context['request'].data.get('macAddress') + sistema = validated_data['sistema'] + client = validated_data['client'] + + existing_devices = Device.objects.filter( + Q(sistema=sistema)& Q(client=client)& Q(macAddress=mac_address) + ) + + if existing_devices.exists(): + # A device with the same macAddress already exists for the given sistema and client + # Get the number of existing devices and add 1 to create a new suffix + suffix = existing_devices.count() + 1 + mac_address += f'_{suffix}' + + validated_data['macAddress']= mac_address return super().create(validated_data) def validate(self, data): diff --git a/Sistemas/views.py b/Sistemas/views.py index a70877a..9abaa6b 100644 --- a/Sistemas/views.py +++ b/Sistemas/views.py @@ -191,6 +191,9 @@ class Sistema_CreateView(CreateView): ========================= API Views ''' + + + class RegisterDeviceView(APIView): permissions_classes = (permissions.AllowAny,)