NhatHo
NhatHo

Reputation: 73

Check multiple Unique columns when using POST method(RestAPI)

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

Answers (2)

Iain Shelvington
Iain Shelvington

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

matt_jay
matt_jay

Reputation: 1271

Might the get_or_create() method help you here?

Upvotes: 0

Related Questions