返回用户(如果存在)或创建新用户

时间:2019-11-07 14:04:47

标签: python django django-rest-framework

我正在尝试在Django / DRF中实现一个视图,该视图给出包含facebook_idfirst_namelast_nameemail的主体,该函数检查是否有用户emailfacebook_id已存在于数据库中。如果没有,那么我创建一个新用户并保存它。

我正在尝试使用serialzier来执行此操作,但是我不确定哪种方法正确。我想使用与注册时使用的序列化器相同的方法:

class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        exclude = ['password']

它包含许多在新视图中不需要的不必要字段(例如电话号码)。我是否应该为此视图创建一个新的Seralizer?我还应该依靠序列化器上的is_valid()函数来告诉我用户是否存在(如果引发错误),或者因为字段可能无效而变得太不可靠了?

这是我到目前为止所拥有的:

@api_view(['POST'])
def facebook_login(request):
    print(request.data)
    serializer = ClientSerializer(data=request.data)
    if serializer.is_valid():
       # create a new user
    else: 
        # possibly perform a get on the database to return the existing user?
    return Response(serializer.errors)

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作。

@api_view(['POST']) 
def facebook_login(request): 
    print(request.data) 
    serializer = ClientSerializer(data=request.data)
    serializer.Meta.read_only_fields = ['x', 'y'] 
    if serializer.is_valid(): 
        # create a new user 
    else: 
        # possibly perform a get on the database to return the existing user? 
    return Response(serializer.errors)

只读字段将是您不希望用户在创建时使用的字段列表,但是您仍然希望在检索时处于视图中。

答案 1 :(得分:0)

您可以使用此

@api_view(['POST'])
def facebook_login(request):
    print(request.data)
    data = request.data
    serializer = ClientSerializer(data=data)
    email = data.get("email")
    obj = Client.objects.filter(email=email)

    if obj.exists():
        return obj

    elif serializer.is_valid():
       f_name = data.get("first_name")
       l_name = data.get("last_name")
       email = data.get("email")
       # more that you need
       Client.objects.create(first_name=f_name, last_name=l_name, email=email, .....)
       return # whatever you want

    else:
        # whatever you want

答案 2 :(得分:0)

我会通过以下方式完成

api_view(['POST'])
def facebook_login(request):
    client = None

    email, fbid = request.data.get('email',None), request.data.get('facebook_id', None)

    # Assuming that email or facebook id is provided, not both

    if email is not None and Client.objects.filter(email=email).exists():
        client = Client.objects.filter(email=email).get()
    elif fbid is not None and Client.objects.filter(facebook_id=fbid).exists():
        client = Client.objects.filter(facebook_id=fbid).get()
    else:
        serializer = ClientSerializer(data=request.data)
        if serializer.is_valid():
            client = serializer.save()
        else:
            return Response(serializer.errors)

    return Response(ClientSerializer(instance=client).data)

可以用某种方式简化它,但这是我的方法。