django unique field
is there another REGEX way (or another way) to ensure that a model class field would be unique? (it is not a key, or at least not declared as a ke开发者_运维知识库y, is shoulb be a simple CharField)
Thanks
The normal way to make a single field unique is to use the unique
argument to the field constructor.
If you need to make this unique on more than one field, have a look at: unique-together
There are two ways of doing so.
The first is to mark the entire column as unique
. For example:
product_name = models.Charfield(max_length=10, unique=True)
This method is good when you want your entire column to be inherently unique regardless of the situation. This can be used for username
, id
, key
etc.
However, if the column cannot be inherently unique but it has to be unique in relation to others, you have to use the manual way.
from django.core.exceptions import ObjectDoesNotExist
try:
n = WishList.objects.get(user=sample_user, product=sample_product)
# already exists
return False
except ObjectDoesNotExist:
# does not exist
wish_list = WishList(user=sample_user, product=sample_product)
wish_list.save()
return True
Take this as an example. You have a wish list which none of the items can be unique. A single user can have many products and a single product can be in the wish list of many users. However, a single user cannot add one particular product to his or her wish list more than once. And this is where unique=True
cannot be used and we have to use try
and except
精彩评论