gpt4 book ai didi

python - Django如何验证用户是否已经存在

转载 作者:行者123 更新时间:2023-12-04 07:56:38 25 4
gpt4 key购买 nike

这是我的模型

class UserAttributes(models.Model):
airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True)
location = PointField(blank=True, null=True)
user = models.ForeignKey(
'users.AerosimpleUser', related_name='user_attributes',
on_delete=models.CASCADE, null=True, blank=True)
View .py
class LocationViewSet(viewsets.ModelViewSet):

serializer_class=LocationRetrieveSerializer
http_method_names = ['get', 'post', 'patch', 'put']

def get_permissions(self):
switcher = {
'create': [IsAuthenticated],
'list': [IsAuthenticated],
'retrieve': [IsAuthenticated],
'update': [IsAuthenticated],
'partial_update': [IsAuthenticated],
}
self.permission_classes = switcher.get(self.action, [IsAdminUser])
return super(self.__class__, self).get_permissions()
def get_queryset(self):
return UserAttributes.objects.filter(
airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk')
序列化程序.py
class LocationRetrieveSerializer(serializers.ModelSerializer):

class Meta:
model = UserAttributes
fields = '__all__'
我想知道用户或机场是否已经存在?

最佳答案

在序列化程序上,实现 create 方法,以便您可以检查用户是否存在。
例子

class LocationRetrieveSerializer(serializers.ModelSerializer):

class Meta:
model = UserAttributes
fields = '__all__'

def create(self, validated_data):
if UserAttributes.objects.filter(user=self.context["request"].user).exists():
raise serializers.ValidationError("User Already exists.")
user_attributes = UserAttributes.objects.create(**validated_data)
return user_attributes

关于python - Django如何验证用户是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66667277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com