Check database records before saving to the database

I am new to Django, and I have a question about databases. Say that I have an application where I do not want the user to be able to save a record to the database if some other user has chose the same information. I have 6 fields in the database, and I do not want a user to have the same data in the six fields as another user (would like to generate a ‘Another user has already made those choices’ message).

Is it possible to do this type of checking? Please let me know and thanks in advance for the help.

There are at least three different ways you can do this, depending upon whether or not you want to enforce this at the database (Model) layer or just within your form.

Probably the easiest / quickest way is to add a unique_together option for that set of six fields. This option will ensure that no two users can ever save data with that same set of values.

Another way would be to add validation to your form, to check whether or not there’s already a row in your table containing that same set of six values. The problem with this is that this wouldn’t prevent someone from using the admin facility from creating this situation - you would need to decide whether or not it’s valid under any circumstance. If there is any valid situation in which you do want to allow this, then this is more flexible than the previous option.

(The third way, which I personally rank lower than the previous two, would be to override the save method on that model to perform a check similar to the previous case. This option has the advantage over the previous option in that it would also apply when someone used the Django admin to edit the model, but doesn’t enforce this restriction within the database itself.)


1 Like

I’d use the firstˆ two options Ken noted together. The unique_together will protect against your code making updating the database to have duplicates. The form validation is then “a layer on top” to show a nice message to the user. That said, Django ModelForms automatically add form validation from unique_together constraints already, so you should only need to customize the message.

From the viewpoint of another person new to Django, I recently stumbled through figuring out what Ken and Adam already mentioned but used thte UniqueConstraint instead of unique_together since the Django docs states that unique_together may be deprecated in the future. From what I could tell though (and I could be wrong), UniqueConstraint is not automatically part of form validation so validation would have to be added otherwise it just returns an error page and not a nice validation error message.

Thanks to everyone for the great advice. I will look into all of them.