django unique field

前端 未结 3 2018
误落风尘
误落风尘 2021-01-18 09:07

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 C

相关标签:
3条回答
  • 2021-01-18 09:42

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

    0 讨论(0)
  • 2021-01-18 09:50

    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

    0 讨论(0)
  • 2021-01-18 10:05

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

    0 讨论(0)
提交回复
热议问题