Reputation: 599
I am trying to insert data on one modal class on destroying another model class. My First model class:
class UserDevice(models.Model):
type = models.ForeignKey(
'Device',
on_delete=models.CASCADE
)
hardware_serial = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
class NewDevice(models.Model):
type = models.ForeignKey(
'Device',
on_delete = models.CASCADE
)
hardware_serial = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
Whenever I will destroy the UserDevice
I want to the same device should be added in NewDevice
My serializer class is :
class UserDeviceSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserSensorDevice
fields = '__all__'
read_only_fields = ['id','created_at']
def create(self, validated_data):
app_id = models.UserDevice.objects.filter(sensor_code= validated_data.get('hardware_serial', None)).first()
if app_id:
msg = _('Application ID is already registered')
raise serializers.ValidationError(msg, code='authorization')
else :
return models.UserDevice.objects.create(**validated_data)
class NewDeviceSerializer(serializers.ModelSerializer):
class Meta:
model = models.NewDevice
fields = '__all__'
read_only_fields = ['id','created_at']
My view class:
class UserSensorRemoveDevice(generics.DestroyAPIView):
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
queryset = models.UserDevice.objects.all()
serializer_class = serializers.UserDeviceSerializer
What I have tried to override UserDevice destroy. But somehow its not working:
def destroy(self, validated_data):
return models.NewDevice.objects.create(type = validated_data.get('type', None),hardware_serial = validated_data.get('hardware_serial', None))
Any help will be highly appreciated. Thanks in advance.
Upvotes: 0
Views: 340
Reputation: 171
in can just override your model UserDevice delete function
def delete(self, using=None, keep_parents=False):
#add new NewDevice instance
super().delete(using, keep_parents,*args,**kwargs)
Upvotes: 0
Reputation: 2752
You can override UserDevice.delete()
method
class UserDevice(models.Model):
...
def delete(self, *args, **kwargs):
NewDevice.objects.create(type=self.type, hardware_serial=self.hardware_serial)
super().delete(*args, **kwargs)
Upvotes: 2