django unique field

2020-04-07 04:10发布

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 key, is shoulb be a simple CharField)

Thanks

3条回答
▲ chillily
2楼-- · 2020-04-07 04:18

The normal way to make a single field unique is to use the unique argument to the field constructor.

查看更多
走好不送
3楼-- · 2020-04-07 04:21

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

查看更多
4楼-- · 2020-04-07 04:23

If you need to make this unique on more than one field, have a look at: unique-together

查看更多
登录 后发表回答