1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

refactor to handle M2M validation in ValidatedModelSerializer

This commit is contained in:
John Anderson
2018-03-01 11:31:56 -05:00
parent 0357d8522c
commit b34f4f8e43

View File

@ -734,30 +734,13 @@ class WritableInterfaceSerializer(ValidatedModelSerializer):
# Validate that all untagged VLANs either belong to the same site as the Interface's parent Deivce or
# VirtualMachine, or are global.
parent = self.instance.parent if self.instance else data.get('device') or data.get('virtual_machine')
tagged_vlans = data.pop('tagged_vlans', [])
for vlan in tagged_vlans:
for vlan in data.get('tagged_vlans', []):
if vlan.site not in [parent, None]:
raise serializers.ValidationError(
"Tagged VLAN {} must belong to the same site as the interface's parent device/VM, or it must be "
"global".format(vlan)
)
validated_data = super(WritableInterfaceSerializer, self).validate(data)
if tagged_vlans:
validated_data['tagged_vlans'] = tagged_vlans
return validated_data
def create(self, validated_data):
"""
Becasue tagged_vlans is a M2M relationship, we have to create the interface first
"""
tagged_vlans = validated_data.pop('tagged_vlans', None)
interface = Interface.objects.create(**validated_data)
interface.save()
if tagged_vlans:
interface.tagged_vlans = tagged_vlans
interface.save()
return interface
return data
#