django独特的领域
是否有另一种 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使单个字段唯一的正常方法是使用
字段构造函数的唯一
参数。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
有两种方法可以做到这一点。
第一个是将整个列标记为
唯一
。例如:product_name = models.Charfield(max_length=10, unique=True)
当您希望整个列在任何情况下都本质上是唯一的时,此方法非常有用。这可用于
username
、id
、key
等。但是,如果列本身不能是唯一的,但在关系中必须是唯一的对于其他人,你必须使用手动方式。
以此为例。您有一个愿望清单,其中没有任何项目是唯一的。一个用户可以拥有许多产品,并且一个产品可以出现在许多用户的愿望清单中。然而,单个用户不能将一种特定产品多次添加到他或她的愿望清单中。这就是不能使用
unique=True
的地方,我们必须使用try
和except
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.
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 usetry
andexcept