How do I check if user exists or not and add or update the database in DRF according to that?

Viewed 161

I am writing an app in which the user inputs either their email or number to continue. If the user only writes one of those, I need to check if either the email or number belong to an existing user so I can use that user. If the user writes both things, I need to check if the user exists (if it does, I use it, if not I create it). If the user exists with only email or number, I need to update the other field that does not match.

I wrote something but I'm not sure how to go on, I'm pretty new at this. This is what I have so far in my serializer:

class OrderSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Order
        fields = '__all__'
        

        def checkuser(self, email, number):

                if order['email'] or order['number'] in User:
                    return User
                elif order['email'] or order['number'] not in User:
                    pass
                elif order['email'] and order['number']:
                    if not in User:
                        UserSerializer()
                    elif order['email'] or order['number']:
                        if User.objects.filter(**validated_data).exists():
                            return User.objects.create(**validated_data)
                
              
1 Answers

you may do like this

class OrderSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Order
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=Order.objects.all(),
                fields=['email', 'number']
        )
    ]
Related