Why make a query before create when unique=True?

52 views
Skip to first unread message

Barış Sermet

unread,
Jan 8, 2021, 8:49:01 AM1/8/21
to Django REST framework
Hi there!

I have User model and serializer class which represents it.

class User(models.Model):
    username = models.CharField(unique=True, max_length=50)
    is_admin = models.BooleanField(default=False)

class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "is_admin")

    def create(self, validated_data: Dict[str, Any]) -> User:
        username = validated_data["username"]

        try:
            user_object = User.objects.create(username=username)
        except IntegrityError:
            raise UserAlreadyRegistered()

        return user_object

My database holds lots of users(appr. 10 million). When I create another user, Django Rest Framework look at the model fields and check that if there are any unique=True fields.
If there are, then it assigns "UniqueValidator". This validator calls "filter_queryset" which means it query the database and check that 
are there any given username record. If there are not, then it creates the user.

My question is, why DRF make a query before create operation? Since database(PostgreSQL) holds the field attributes, it knows that 
username field is unique, and it can throw an exception if I try to create user with the same username field. The reason I'm asking it, my application 
gets a lot of create operation, and each create operation I have to query my database, which is I think more costly than create it wihout making a filter query. 
Do I missing something in this operation?

Thanks!

Praveen chaduvala

unread,
Jan 11, 2021, 1:25:52 AM1/11/21
to Django REST framework
Once try this may be usefull for you & **(my english is not good )just look at code
I am also getting this error using with "unique ", field i solved this my own way.
write serializers like this and dont write try,a dn except in serializers , define inside the function ,
 my user serializer ,
class UserSerializer(serializers.ModelSerializer):
# mobile = serializers.RegexField("[0-9]{10}",min_length=10,max_length=10)
# doctor_clinic=ClinicSerializer(read_only=True,many=True)
password = serializers.CharField(write_only=True)
email=serializers.EmailField(max_length=155,min_length=3,required=True)
name=serializers.CharField(max_length=55,min_length=3,required=True)

class Meta:
model = DoctorProfile
fields = ("id","name", "email", "password", "mobile","otp","dob","gender")
# fields="__all__"



def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
and 
my views

class RegisterApi(generics.GenericAPIView):
serializer_class = UserSerializer
authentication_classes = []

def post(self, request, *args, **kwargs):
parameters = request.data.copy()
parameters['otp'] = random.randrange(1000, 10000)
serializer = self.get_serializer(data=parameters)
if serializer.is_valid(raise_exception=True):
serializer.save()

return Response({"message": "User Created Successfully. Now perform Login to get your token"},status=status.HTTP_201_CREATED)
else:
return Response({'Mobile number already exist'},status=status.HTTP_406_NOT_ACCEPTABLE)

Barış Sermet

unread,
Jan 11, 2021, 8:56:34 AM1/11/21
to Django REST framework
I'm not getting any error. I wonder why DRF make a select query on database before creating and object when object has unique=True field.

11 Ocak 2021 Pazartesi tarihinde saat 09:25:52 UTC+3 itibarıyla pchad...@gmail.com şunları yazdı:

Praveen chaduvala

unread,
Jan 12, 2021, 7:11:50 AM1/12/21
to Django REST framework
Reply all
Reply to author
Forward
0 new messages