Django - Slugify 获取查找
如果我有一个名为 Object 1
的对象,并且我想要 get()
该对象,但我试图使用一个 slugified 名称 object- 来获取它1、有什么办法可以做到这一点吗?比如:
Model.objects.get(name__slugify = slugifiedname)
如果可能的话,我想避免在我的模型中添加额外的 slug 字段。
If I had an object with the name Object 1
and I wanted to get()
that object, but I was trying to get it with a slugified name object-1
, is there any way to do this? Something like:
Model.objects.get(name__slugify = slugifiedname)
I want to avoid adding an extra slug field to my model if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要对“名称”字段的值进行一些限制,仅允许 [-A-Za-z]+,但您可以这样做:
但是,您通过查询字符串传递的名称必须与数据库。 YMMV。我的建议是,使用 SlugField :)
You would need to put some restrictions on the value of the 'name' field only allowing [-A-Za-z]+, but you could do:
However, the name you pass through the querystring would have to be exactly what's in the database. YMMV. My advice, use a SlugField :)
Slugify 是一个 Python 函数。为了实现您的目标,Django 必须获取完整的数据库(至少包含 pk 和
name
字段),计算每行的 slug 并将其与给定参数进行比较。这将是非常低效的,所以:TLDR:不
Slugify is a Python function. To achieve your goal, Django would have to fetch the complete database (with at least the pk and the
name
field), calculate the slug for each row and compare this to the given parameter. And this would be very imperformant, so:TLDR: No