我一直试图从用户表(mysql)中删除一个现有的示例,但我一直从用户那里得到错误。delete()这是我的观点:
@api_view(['GET', 'PUT', 'DELETE'])
def user_api_id(request):
try:
id = request.GET.get('id')
user = User.objects.get(pk=id)
if request.method == 'GET':
serializer = UserSerializer(user)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = UserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
try:
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except ValidationError as ve:
return Response({"error": str(ve)}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
字符串
当我启动一个DELETE请求时,我会得到这样的结果:
第一个月
(btw我要删除的用户的id ='john')
这是我的用户模型:
class User(models.Model):
id = models.CharField(primary_key=True, max_length=50)
password = models.CharField(max_length=50)
name = models.CharField(max_length=25)
lastname = models.CharField(max_length=25)
age = models.IntegerField()
gender = models.CharField(max_length=6)
email = models.CharField(max_length=50, blank=True, null=True)
phone = models.CharField(max_length=50, blank=True, null=True)
address = models.CharField(max_length=50, blank=True, null=True)
educationallevel = models.CharField(db_column='educationalLevel', max_length=50, blank=True, null=True) # Field name made lowercase.
experience = models.CharField(max_length=20, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_anonymous = models.BooleanField(default=False)
is_authenticated = models.BooleanField(default=True)
USERNAME_FIELD = 'id'
REQUIRED_FIELDS = []
class Meta:
managed = False
db_table = 'user'
型
这是数据库中的用户表:
CREATE TABLE `user` (
`id` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
`password` varchar(50) COLLATE utf8mb4_general_ci NOT NULL,
`name` varchar(25) COLLATE utf8mb4_general_ci NOT NULL,
`lastname` varchar(25) COLLATE utf8mb4_general_ci NOT NULL,
`age` int NOT NULL,
`gender` enum('male','female') COLLATE utf8mb4_general_ci NOT NULL,
`email` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
`phone` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
`address` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
`educationalLevel` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
`experience` varchar(20) COLLATE utf8mb4_general_ci DEFAULT NULL,
`is_anonymous` tinyint(1) DEFAULT '0',
`is_authenticated` tinyint(1) DEFAULT '1',
`is_active` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
)
型
我试着直接从数据库中删除,它的工作原理如预期。尝试传递一个不存在的id,它返回了用户DOESNOTEXIT。此外,用户表中的id字段在db中的其他表中被引用为外键,但只有用户表有数据。
1条答案
按热度按时间zy1mlcev1#
我通过将INSTALLED_APPS中的
'django.contrib.admin'
转换为注解来解决这个问题。