0
# models.py
class clients(models.Model):
    client_id = models.CharField(max_length=8,unique=True, null=False, blank=True,primary_key=True)
    client_identity_id = models.IntegerField(unique=True, null=False, blank=False)
    ...


#serializer.py
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = clients
        fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num')
        read_only_fields = ('money',)
        def create(self, validated_data, **kwargs):
            validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) 
                                                  for i in range(8))
            return clients.objects.create(**validated_data)


#views.py :
def post(self,request):
    data=request.data
    serializer = UserSerializer(data=data)
    if serializer.is_valid():
        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

When I make a post request it should generate a unique client_id for the user , but it's staying Null.

Please help me using included code instead of showing alternative ways to set value for client_id. Thanks

gtalarico
  • 4,409
  • 1
  • 20
  • 42
Ahmad Mardene
  • 47
  • 1
  • 6

1 Answers1

0

I executed the same code and it worked fine.

serializer =UserSerializer(data={})
assert serializer.is_valid()
obj = serializer.save()
print(obj.client_id)
'6I2N4GC3'

From your code, looks like you create method might not be called because it's indented inside Meta.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = clients
        fields = ...

        # Indented inside Meta
        def create(self, validated_data, **kwargs):

    # Should be sibling to Meta
    def create(self, validated_data, **kwargs):
        ...
gtalarico
  • 4,409
  • 1
  • 20
  • 42
  • thank you , any code suggestion to add to make it unique and do not repeat another old id ?? – Ahmad Mardene Apr 28 '20 at 19:21
  • Your welcome. You should search SO or post that as a separate question. As for my personal opinion on the approach, I would use uuid instead and add default generation code on model, similar to one of these answers https://stackoverflow.com/a/16925164/4411196 – gtalarico Apr 28 '20 at 19:27