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

标签 python django django-models django-rest-framework django-views

这是我的模型

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/

相关文章:

django - 在 Django 中创建模板时迭代模型属性

python - 使用线程将 stdout 重定向到 Tkinter 文本小部件的问题

python - 点聚类算法

python - 终止 Python 程序

django - 如何在 Cloud Run 的日志中显示 django 日志记录和错误日志?

django - 覆盖保存方法 - 'ImageFile' 对象没有属性 '_committed'

python - 使用通配符键元素访问 Python 字典

python - Django 设置.py 错误 : Import by filename is not supported

javascript - 新手网络开发者想要添加网页设计和交互

python - Django管理界面: how to show different model based on a user's selection?