Check existing user when using POST method

87 views
Skip to first unread message

Trieu Tran Quoc

unread,
Jul 5, 2015, 5:23:32 AM7/5/15
to django-res...@googlegroups.com
When we call api "localhost:8000/user/" (POST method) to add new user, if user's existing (user_id is already existing), api return a response normally.
How we can check if a user's existing and raise an existing error?
Database is Cassandra.
view:
class UserList(APIView):
def post(self, request):
try:
# add user
serializer = UserSerializer(data=request.data)
if serializer.is_valid(True):
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(status=status.HTTP_400_BAD_REQUEST)
except:
print("Unexpected error:", sys.exc_info())
raise
serializer:
class UserSerializer(serializers.Serializer):
def create(self, validated_data):
return User.objects.create(**validated_data)

def update(self, instance, validated_data):
instance.user_id = validated_data.get('user_id', instance.user_id)
instance.gold = validated_data.get('gold', instance.gold)
instance.save()

user_id = serializers.CharField(required=True)
gold = serializers.IntegerField(required=False)
model:
class User(Model):
user_id = columns.Text(max_length=64, primary_key=True, db_field='user_id')
display_name = columns.Text(max_length=64)
gold = columns.Integer(default=0)
passing_level = columns.Integer(default=0)
live_num = columns.Integer(default=0)
create_time = columns.DateTime()
last_update = columns.DateTime()
Message has been deleted

Juan Gutierrez

unread,
Jul 5, 2015, 10:47:36 AM7/5/15
to django-res...@googlegroups.com
Hi Trieu,

You may just be able to update your serializer's "create" method to simply do a database lookup against the validated data:

class UserSerializer(serializers.Serializer):
    
def create(self, validated_data):

        
if User.objects.filter(**validated_data).exists():
            
raise Exception('User already exists')
            # Or return 404...or do something else
        return User.objects.create(**validated_data)

However, that operation sounds more like a "validation" - so it would probably be more appropriate to do so by overriding the serializer's validate method:

class UserSerializer(serializers.Serializer):
    
def create(self, validated_data):
        
return User.objects.create(**validated_data)

    
def validate(self, data):
       data 
= super(UserSerializer, self).validate(data)
       
if User.objects.filter(**validated_data).exists():
           raise serializers.ValidationError("User already exists")
       return data


Personally, I would restructure your code a bit to leverage more of the framework's built in functionality.

You could turn your serializer into a ModelSerializer and associate your User model with it (see: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer). Then, update your view to use a CreateModelMixin (see: http://www.django-rest-framework.org/api-guide/generic-views/#createmodelmixin). Even after that, to achieve the desired functionality you described originally, I believe the preferred method would still be to override the serializer's validate method.

Trieu Tran Quoc

unread,
Jul 5, 2015, 11:33:40 AM7/5/15
to django-res...@googlegroups.com
Thanks Juan,
I try using filter but I got an error: 'ModelQuerySet' object has no attribute 'exists' 
This is also a problem I'm facing when interact with Cassandra from DRF, maybe because I'm using django-cassandra-engine model, not django model.
But I understand your mean, thank you :)

Another question about using filter with multiple params, if you know how to do this, please suggest me.
Thank you very much :)

Juan Gutierrez

unread,
Jul 5, 2015, 1:08:54 PM7/5/15
to django-res...@googlegroups.com
Hi Trieu,

The AttributeError exception about the "exists" method is most likely due to the django-cassandra-engine model implementation, which, unfortunately, I am unfamiliar with. 

The best advice I can give is review the django-cassandra-engine documentation to see what they say about record existence checks and filtering with multiple parameters. Hopefully, someone else with django-cassandra-engine experience will be able to follow up with you regarding your questions.

Trieu Tran Quoc

unread,
Jul 6, 2015, 10:40:21 AM7/6/15
to django-res...@googlegroups.com
Thanks Juan, but I can't find anything about this :(
Reply all
Reply to author
Forward
0 new messages