Hello, everyone. I am working on Django rest. I have a serializer like this.
uniqid = serializers.ReadOnlyField(read_only=True)
customer_terms_conditions = serializers.ReadOnlyField(read_only=True)
model = DrycleanMcustomerinfomaster
fields = ['uniqid', 'customer_first_name', 'customer_phone', 'customer_email_address','customer_terms_conditions','frenchise']
I have model class:
serializer_class = CustomerSerializer
#Inrementing the 'UniqID' manually.
def perform_create(self, serializer):
top = DrycleanMcustomerinfomaster.objects.select_for_update(nowait=True).order_by('uniqid').latest('uniqid')
uniqid = top.uniqid + 1
suggestion needed. I want to validate the entities. eg I want to place a check on the email field. If email already exists throw a response error.
solution: I can write a query for it. There will be many queries for every field? I don’t want to make multiple queries. Is there any other way to do the validations? Something needs to do with the serializer class. Anyone can help.
First, for validations, I’d be adding them to the model and not trying to do it in the view.
See Validators | Django documentation | Django.
Also, I would be remiss if I didn’t highlight @adamchainz blog posts on constraints:
I’m highlighting all of them to give you a broad range of ideas of what can be done with them.
The other item I’ll point out is that your code has a race condition for setting the uniqid. There’s no guarantee that you’re going to get a unique value. You should be using your database’s mechanics for assigning that value. (e.g. A sequence if you’re using PostgreSQL)
Thank you for the insight.
For the ‘UniqID’ I am using MS SQL server. I cannot change the existing column to an identity column. Either I have to drop the column or remove all data then make it as an identity column.
I am adding the ‘UniID’ manually. I used the @transaction.atomic In order to if there is an exception while saving data it will roll back the query. If is there any good solution for it. would be a help. Thanks
For your sequences, try django-sequences: GitHub - aaugustin/django-sequences: Generate gapless sequences of integer values. . It’s not tested on MS SQL, but ofc few packages are. It may just work!
While I agree with Adam’s answer above, you have a second option.
If that package doesn’t work for you, or if performance is more important than avoiding gaps in the sequence, you may also be able to implement an MS SQL Sequence object external to your table and access it for your values.
(I don’t know how this would necessary work in Django with the ORM, and I don’t have an instance of SQL Server available to me right now to try - but if you were to go this route, there’s a chance you might need to create a raw SQL query to retrieve the next value.)
Thank you for the feedback.