我有一个代表设备标识符的模型,我想在设备标识符和当前用户上创建一个唯一约束。 我在save方法上传递用户但是我不得不删除约束,现在我正在尝试编写测试,我编写的糟糕代码变得难以测试。如何编写序列化程序,我可以将currentuser设置为默认值,并保留模型上的唯一对比。
这是我的模特
class DeviceIdentifier(models.Model):
owner = models.ForeignKey(HDSAuthUser, primary_key=True, on_delete=models.CASCADE)
id_device = models.UUIDField(primary_key=True)
insert_date = models.DateTimeField(auto_now_add=True)
这是我的序列化程序
class DeviceIdentifierSerializer(serializers.ModelSerializer):
"""
Device identifier serializer
"""
class Meta:
model = DeviceIdentifier
fields = ('id_device', 'owner')
这是我的观点
class RegisterDevice(CreateAPIView):
"""
View for registering device for the logged user
"""
serializer_class = DeviceIdentifierSerializer
def post(self, request, *args, **kwargs):
obj = DeviceIdentifierSerializer(data=request.data)
obj.is_valid()
obj.save(owner=request.user)
return Response(True)
答案 0 :(得分:0)
在模型上添加唯一的constaint而不是Model Serializer,它肯定会起作用。
class DeviceIdentifier(models.Model):
owner = models.ForeignKey(HDSAuthUser, on_delete=models.CASCADE)
id_device = models.UUIDField(primary_key=True)
insert_date = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('field1', 'field2',)
class DeviceIdentifierSerializer(serializers.ModelSerializer):
"""
Device identifier serializer
"""
class Meta:
model = DeviceIdentifier