Reputation: 33
I am new to django and web frameworks. I am trying to filter models in django given a substring of its attribute Group
pack=My_pack.objects.get(Group=sumthing)
now my Group attribute contains a pair of values sepearted by "/" for eg
Group="System/Application"
and i want to filter model given only one value suppose "System", then how to do dat????
Upvotes: 3
Views: 157
Reputation: 4051
you can use filter in django in different ways,
My_pack.objects.get would bring only one instance , if multiple instance are present here it would give you error. so you need to enclose this into try except blocks.
pack = My_pack.objects.get(group__icontains='System')
on the other hand
My_pack.objects.filter would bring more than one instance and if no instance found it would bring and empty list []
pack = My_pack.objects.filter(group__startswith='System')
also you can use one of the shortcut functions named get_object_or_404
. This works similar as get. the difference is you do not need to enclose it in try except block. If it bring the instance it would give the instance as the return value but it does not find any instance then it would throw a 404 status message.
pack = get_object_or_404(My_pack, group__startswith='System')
Upvotes: 1
Reputation: 50177
You're looking for the startswith
field filter:
pack = My_pack.objects.filter(group__startswith='System')
Upvotes: 2
Reputation: 47172
This would be the syntax for this query:
pack = My_pack.objects.get(group__icontains='System')
Upvotes: 1
Reputation: 34553
A great place to start would be The Definitive Guide to Django. Try checking out the QuerySet API Reference in the docs.
https://docs.djangoproject.com/en/1.5/ref/models/querysets/#icontains
Your code as it stands, won't work. use:
pack = My_pack.objects.filter(Group__icontains='System')
Upvotes: 0