Django MongoDB Queryset can't print or iterate - django

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

Related

ascending=True not working in django-mptt

Hi good day I'm currently following Django-MPTT documentation and I have a problem using ascending=True. Here's my code:
views.py
def show_genres(request):
Try01 = Genre.objects.filter(name="Rock")
context = {'genres': Genre.objects.all(),
'sample_ancestor': Try01.get_ancestors(ascending=True, include_self=True)}
return render(request, "sampletemp/startup.html", context)
when I'm using ascending=True an error occurs saying:
Exception Value: get_queryset_ancestors() got an unexpected keyword argument 'ascending'
How can I fix it. Thank you in advance!
You are using the wrong method
models.get_ancestors has an ascending field see here
managers.TreeManager.get_queryset_ancestors howerver has not, as shown here

Django query params to array

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', '')

Why is Django Paramaterized query not working

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.

haystack SearchQuerySet() is returning list instead of SearchQuerySet object

this is my get_queryset(): method in the view
def get_queryset(self):
#by here the search query is getting executed
self.vendor_filter=self.request.GET.get('select_vendor', 'all')
self.search_query=self.request.GET.get('q', "")
self.sort_by=self.request.GET.get('sort_by', "relevance")
queryset=SearchQuerySet().all()[:50]
return queryset
this method is throwing 'list' object has no attribute 'all' error. However I ran this SearchQuerySet().all() in django shell it is returning correct results.
.
it is very annoying issue. I dont know what is the mistake?, I am using whoosh with django-haystack search.
I found the reason why, the code queryset=SearchQuerySet().all()[:50] was converting the SearchQuerySet object to list. I changed it to queryset=SearchQuerySet().all() now it works as expected. It took me whole day to figure out. But still I don't know why it was doing that without throwing an exception or error.

Django-haystack (xapian) autocomplete giving incomplete results

I have a django site running django-haystack with xapian as a back end. I got my autocomplete working, but it's giving back weird results. The results coming back from the searchqueryset are incomplete.
For example, I have the following data...
['test', 'test 1', 'test 2']
And if I type in 't', 'te', or 'tes' I get nothing back. However, if I type in 'test' I get back all of the results, as would be expected.
I have something looking like this...
results = SearchQuerySet().autocomplete(auto=q).values('auto')
And my search index looks like this...
class FacilityIndex(SearchIndex):
text = CharField(document=True, use_template=True)
created = DateTimeField(model_attr='created')
auto = EdgeNgramField(model_attr='name')
def get_model(self):
return Facility
def index_queryset(self):
return self.get_model().objects.filter(created__lte=datetime.datetime.now())
Any tips are appreciated. Thanks.
A bit late, but you need to check the min ngram size that is being indexed. It is most likely 4 chars, so it won't match on anything with fewer chars than that. I am not a Xapian user though, so I don't know how to change this configuration option for that backend.