django独特的领域

发布于 2024-09-08 06:30:25 字数 92 浏览 1 评论 0原文

是否有另一种 REGEX 方法(或其他方法)来确保模型类字段是唯一的? (它不是一个键,或者至少没有声明为键,应该是一个简单的 CharField)

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笑着哭最痛 2024-09-15 06:30:25

使单个字段唯一的正常方法是使用 字段构造函数的唯一 参数。

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

自找没趣 2024-09-15 06:30:25

如果您需要在多个领域使其独一无二,请查看:
独特在一起

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

疑心病 2024-09-15 06:30:25

有两种方法可以做到这一点。
第一个是将整个列标记为唯一。例如:
product_name = models.Charfield(max_length=10, unique=True)

当您希望整个列在任何情况下都本质上是唯一的时,此方法非常有用。这可用于 usernameidkey 等。

但是,如果列本身不能是唯一的,但在关系中必须是唯一的对于其他人,你必须使用手动方式。

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

以此为例。您有一个愿望清单,其中没有任何项目是唯一的。一个用户可以拥有许多产品,并且一个产品可以出现在许多用户的愿望清单中。然而,单个用户不能将一种特定产品多次添加到他或她的愿望清单中。这就是不能使用 unique=True 的地方,我们必须使用 tryexcept

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文