Skip to content

Commit

Permalink
refactor(itam): update device software serializer validator
Browse files Browse the repository at this point in the history
ref: #248 #391
  • Loading branch information
jon-nfc committed Nov 22, 2024
1 parent 8828a36 commit 292ee87
Showing 1 changed file with 28 additions and 25 deletions.
53 changes: 28 additions & 25 deletions app/itam/serializers/device_software.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from api.serializers import common

from core import exceptions as centurion_exception
from core.fields.badge import Badge, BadgeField

from itam.models.device import Device, DeviceSoftware
Expand Down Expand Up @@ -68,6 +69,10 @@ def get_url(self, obj) -> dict:

category = SoftwareCategoryBaseSerializer(many=False, read_only=True, source='software.category')

device = serializers.PrimaryKeyRelatedField(write_only = True, required = False, queryset=Device.objects.all() )

software = serializers.PrimaryKeyRelatedField(write_only = True, required = False, queryset=Software.objects.all() )


class Meta:

Expand Down Expand Up @@ -101,51 +106,49 @@ class Meta:
]


def get_field_names(self, declared_fields, info):
def validate(self, data):


if 'view' in self._context:

if 'device_id' in self._context['view'].kwargs:

self.Meta.read_only_fields += [
'device'
]
device = Device.objects.get(id=self._context['view'].kwargs['device_id'])

data['device'] = device
data['organization'] = device.organization

if 'software_id' in self._context['view'].kwargs:

self.Meta.read_only_fields += [
'software'
]
software = Software.objects.get(id=int(self._context['view'].kwargs['software_id']))

fields = super().get_field_names(declared_fields = declared_fields, info = info)
data['software'] = software

return fields
if 'device' in data:

data['organization'] = data['device'].organization

def is_valid(self, *, raise_exception=False):

is_valid = super().is_valid(raise_exception=raise_exception)
if not data.get('device'):

if 'view' in self._context:

if 'device_id' in self._context['view'].kwargs:

device = Device.objects.get(id=self._context['view'].kwargs['device_id'])

self.validated_data['device'] = device
self.validated_data['organization'] = device.organization

if 'software_id' in self._context['view'].kwargs:
centurion_exception.ValidationError(
detail = {
'device': 'This field is required',
'code': 'required'
}
)

software = Software.objects.get(id=self._context['view'].kwargs['software_id'])

self.validated_data['software'] = software
self.validated_data['organization'] = self.validated_data['device'].organization
if not data.get('software'):

centurion_exception.ValidationError(
detail = {
'software': 'This field is required',
'code': 'required'
}
)

return is_valid
return data



Expand Down

0 comments on commit 292ee87

Please sign in to comment.