Reputation: 73
Pretend that I have multiple unique columns in my database.
username = models.CharField(max_length=64, unique=True)
email = models.CharField(max_length=64, unique=True)
phone_number = models.CharField(max_length=64, unique=True)
serial_number = models.CharField(max_length=64, unique=True)
When I use POST method, I will use 4 queries to check each of these field exist in database.(If not then I will POST them in database)
I am wondering is there a smarter way to check all multiple unique in the database?
Upvotes: 0
Views: 41
Reputation: 32274
You could create a query that matches any existing records where any of the fields match using OR
via Q
objects. Q
objects can be used to create OR
filters by chaining them with the |
operator
fields_are_not_unique = YourModel.objects.filter(
Q(username=form.cleaned_data['username'])
| Q(email=form.cleaned_data['email'])
| Q(phone_number=form.cleaned_data['phone_number'])
| Q(serial_number=form.cleaned_data['serial_number'])
).exists()
Upvotes: 1