Django - Slugify get lookup
If I had an object with the name Object 1
and I wanted to get()
that object, but I was trying to g开发者_开发知识库et 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.
You would need to put some restrictions on the value of the 'name' field only allowing [-A-Za-z]+, but you could do:
def my_request(request, name):
un_slugified_name = name.replace('-', '')
objects = MyModel.objects.get(name=unslugified_name)
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 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
精彩评论