I am trying to get the results from an array as explained here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#in
http://127.0.0.1:8000/blogs?years=['2018', '2019']
http://127.0.0.1:8000/blogs?years=[2018, 2019]
Turns out ['2018', '2019'] is not what i am getting as years , even though visually they look exactly the same.
I even tried using getlist as explained here how to get multiple results using same query params django this does produce the desired results
def get_queryset(self):
years = self.request.query_params.get('years')
return self.queryset.filter(year__in=years)
Any clue on what am i doing wrong here?
I tried all options it does not work, while i type in the below statement it works perfectly fine
def get_queryset(self):
return self.queryset.filter(year__in=['2018', '2019'])
I don't believe this way will work. When you pass the value in querystring, I guess Django will recieve as a string.
- EDIT -
The above answer wont work is need to add more years, I got the solution 127.0.0.1:8000/blogs?years=2018&years=2019 and
years = self.request.query_params.getlist('years', '')
converts this to list.
– #indavinci
I think a better a better and cleaner way to solve this problem is to just pass the string as comma-separated values in query params and split them up in your Django View.
URL:
http://127.0.0.1:8000/blogs?years=2018,2019
Your View:
def get_queryset(self):
years = self.request.query_params.get('years').split(',')
return self.queryset.filter(year__in=years)
If you have function based view this should work:
request.GET.getlist('years', '')
Related
I have a view which should accept an end point with a query parameter, as well as without a parameter.
http://localhost:8001/v1/subjects?owner_ids=62,144
and
http://localhost:8001/v1/subjects
Here's my view file...
class SubjectPagination(JsonApiPageNumberPagination):
"""
Required for frontend to retrieve full list.
"""
max_page_size = 5000
class SubjectViewSet(Subject.get_viewset()):
pagination_class = SubjectPagination
def get_queryset(self):
import pdb; pdb.set_trace()
queryset = Subject.objects.all()
if self.request.GET['owner_ids']:
owner_id_list = self.request.GET['owner_ids'].split(',')
owner_id_list_integer = []
for i in owner_id_list:
owner_id_list_integer.append(int(i))
return queryset.filter(organization__in=owner_id_list_integer)
else:
return queryset
SubjectUserRoleViewSet = Subject.get_by_user_role_viewset(
SubjectViewSet, GroupRoleMap, Role)
I am trying to figure out how to handle both the end points? Please advice what needs to be done at the view to handle a URI with or without query strings?
Here's the urls.py
router.register(r'subjects', views.SubjectViewSet)
First of all, is a good practice to send the parameters in url-form-encode, avoiding things like that, in this case for send a list you could send id as:
?owner_ids[]=62&owner_ids[]=144
the querydict its going to be like this :
<QueryDict: {'owner_ids[]': ['62', '144']}>
and you could process it easily, like this
self.request.GET.getlist('owner_ids[]', [])
remember to use the get and get list functions of the request method GET and POST, to avoid dict errors.
Second, split returns a list the for statement in owner list id is totally unnecessary, and the queryset statement __in accept array of strings, if you actually want to convert all the items to integers use list comprehensions. For example, to convert all the items in a list to integer, just have to use:
owner_ids = [int(i) for i in owner_ids ]
this is way more fast in python and way more pythonic, and also cool too see.
and last, all urls should finish in /, even django has a settings for that called append_slash
this is what i can tell about the ambiguous question you are asking, in the next times please write questions more precisely that help people help you.
I have been struggling with this simple query in django. I have checked a lot over internet. I tried using similar syntax - yet no luck.
In my application on html page I need to display some specific record. And for that i want to use parameterized select statement. But the query is not working..
I have checked id2 is getting correct value from previous html page..
And I know I can use APIs but for my databases classes I need to use raw queries in my application.
Can someone please help me here...
def details(request, id2):
temp = 'test3'
data = Posts.objects.raw('''select * from posts_posts where posts_posts.id = %s ''', id2)
context ={
'post' : data,
If you run that code you will see an error, since that is not the correct format for a call to raw. If you can't see the error output anywhere, then you have yet another problem for another post.
The correct format for raw is: .raw(sql, iterable-values), like this:
posts = Posts.objects.raw("select * ..", [id2, ]) # or use (id2,) for a tuple
<RawQuerySet: select * from ... where id = 5>
To get the actual list, since that just gives you a Query, you need to evaluate it somehow:
posts_list = list(posts)
first_post = posts[0]
Be careful, if you don't evaluate the QuerySet then it can be re-run a second time. Please convert it to a list() before doing further operations on it.
There is urls.py pattern.
url(r'^notice/(?P<article>[0-9]\d+)/', web.views.notice),
Here is views.py
def notice(request, article):
data = article
return render(request, "notice.html")
However, web brower shows 404 Error.
If I remove add parameter, it is ok.
What I am wrong?
Intended result (Blog style, not get parameter)
/notice/1, /notice/2, ...
I think what is happening is that [0-9]\d+ is expecting at least a 2-digit number, one digit for the [0-9] and then one or more digits following that due to the \d+. I believe what you really want is just
url(r'^notice/(?P<article>\d+)$', 'web.views.notice')
I don't know why you use d???
url(r'^issue/(?P<issue_id>[0-9]+)$', views.issue, name='issue'),
url(r'^project/(?P<pk>.*)$', login_required(views.ProjectView.as_view()), name='project'),
Based on the question you asked, I am getting that you want to display the data on the template based on the parameter passed in the URL.Let me try to explain it step by step:
First lets say you have the following url:
url(r'^notice/(?P<article>\d+)$', views.notice,name="notice")
Now lets define the view for fetching the data from the model, based on the parameter in the URL, i am assuming you are passing the PK in the URL:
def notice(request, article):
data = YourModelName.objects.get(id=article)
//Passing back the result to the template
context={"article":data}
return render(request, "notice.html",context)
Now in your template you can access the data as such:
{{ article.field_name }}
Hope this helps you out!!!!
I try to execute a MongoDB raw query in Django of the type:
queryset= ObjectClass.objects(__raw__={ })
if I want to print the queryset or iterate I get the following error message:
"error_message": "cannot convert value of type <class 'mongoengine.queryset.QuerySet'> to bson",
Any suggestions why this happens, I couldn't find a suitable answer so far, thanks for any hints
Jonas
just a shot into the dark since I m not able to try it out by myself in the moment, since I uninstalled mongodb. But in the back of my mind I remember that I had a similar problem.
Try:
queryset= list(ObjectClass.objects(__raw__={ }))
for result in queryset:
print result
I am using Django-taggit and works fine for me but the exclude has a problem.
Keyword is a string like 'key1 key2 key3'. The code is:
keyword = form.cleaned_data['keyword']
qlist = lambda x: [Q(name__icontains=x), Q(author__name__icontains=x),Q(tags__name__icontains=x)]
item_list = Item.objects.distinct()
for key in keyword.split():
if ('-'==key[0]):
print 'exclude: %s'%(key[1:])
item_list = item_list.exclude(reduce(operator.or_,qlist(key[1:])))
else:
print 'include: %s'%(key)
item_list = item_list.filter(reduce(operator.or_,qlist(key)))
It works fine for filter() and for the exclude() Q(name_icontains=x), Q(author_name_icontains=x).
But, when I try to use exclude() with Q(tags_name__icontains=x) it doesnt work.
Regards,
Cristian
I'm not really too versed in taggit intricacies, but... Looking at the code, it seems like the "name" is dynamically built in a lazy way.
So, if you're not populating the query explicitly, you're going to get empty request, so Q(tags__name__icontains=key) will be empty, and exclude(...) will just be like filter(not null).
Try to force populating the tag query via a select_related() or something similar.
I think, It is not supported. I found this link:
https://github.com/alex/django-taggit/issues/31