I want to retrieve all indexes under elasticsearch index folder. I got this error.
UnboundLocalError at /tjobfucksearch/
local variable 'results' referenced before assignment
my views.py
from haystack.query import SearchQuerySet
def fucksearch(request):
query = request.GET.get('q', '')
if query:
results = SearchQuerySet().all()
return render_to_response("tjob/fucksearch.html", {
"results": results,
"query": query
})
my urls.py
url(r'^tjobfucksearch/$', 'tjob.views.fucksearch'),
Plus: haystack 2.0.0, django 1.4
Any advice would be appreciated. Plz help me.
Consider the case where no q parameter is provided. Then query is set to '', the if query condition fails, so results is not set (not even set to None; Python doesn't know about the name results at this point). So it fails when you try to get the value from results to pass it into the context dict for render_to_response. Perhaps add:
results = None
before:
if query:
....
This way, results will always be defined by the time you need to pass it to render. (You still have to handle the none-results case in your template!)
Related
I have a few useQuery() calls in my react component like this:
const {...} = useQuery(["person.getAll", ....
const {...} = useQuery(["person.getCounts", ....
Then later in a click event after some DELETE/POST request is finished I try to invalidate above queries:
queryClient.invalidateQueries("person");
But it does not trigger the re-fetch.
I thought it's some state management issues from my part but then I tried invalidating a specific query like
queryClient.invalidateQueries("person.getAll");
and it works fine..
Is partial query key matching not working in react-query ?
React-Query invalidation works off based array prefixes, not string prefixes.
Your useQuery calls should look like this:
const {...} = useQuery(["person", "getAll", ....
const {...} = useQuery(["person", "getCounts", ....
And then you invalidateQueries call will work, with a slight change:
queryClient.invalidateQueries({
queryKey: ["person"]
}); // invalidate all query keys which start with "person"
queryClient.invalidateQueries(["person"]); // this also works
Alternative, if you are locked into your current syntax, you can accomplish the same using a predicate:
queryClient.invalidateQueries({
predicate: query =>
query.queryKey[0].startsWith("person"),
})
But this breaks the React-Query convention.
If you see the last example in the invalidateQueries docs, it provides an option for maximum granularity
If you find yourself wanting even more granularity, you can pass a predicate function to the invalidateQueries method. This function will receive each Query instance from the query cache and allow you to return true or false for whether you want to invalidate that query:
So, for your scenario the following should work
queryClient.invalidateQueries({
predicate: query =>
query.queryKey[0].startsWith('person'),
})
This is a matter of how you are structuring the queryKey array. The first constant value of your queryKey array is a whole string, based on what you provided the partial matching won't work if you try to invalidate the queries based on just a part of that string. For this to work, you'd need to structure the queryKey array like so:
const {...} = useQuery(["person", "getAll", ....
const {...} = useQuery(["person", "getCounts", ....
Now the invalidation should work as expected because it's matching all queries that start with "person" in their query key:
queryClient.invalidateQueries(["person"]);
Reference of this on the docs
I have a structure that looks kind of like this:
{
'foo': 'bar',
'isBaz': false
}
and the following Repository code
repository.findByIsBazIsFalse();
I figured that would only return records where isBaz is false, but it's also returning records where isBaz is set to true. My initial guess is that the field starts with the word 'is' which is a reserved keyword in the spring/mongo query.
FWIW I also tried via annotation but no luck
#Query("{isBaz:false}")
Does anyone know how to make it work without renaming the variable to 'baz'?
Make sure this field is defined as boolean and it should work!
private boolean isBaz;
repository.findByIsBazIsFalse();
[main] o.m.d.p.c :Sending command '{"find": "collection", "filter": {"isBaz": false}, ...}'
For ref, using "#apollo/client": "^3.5.5",
I've defined my typePolicies like so as suggested in docs:
HistoricalData: {
keyFields: ["variable", "workspace"],
fields:{...}
}
and when my cache is built, I am expecting my cacheId to be like
<__typename>:<id>:<id>
HistoricalData:${props.variable}:${props.workspace}`;
but instead, when I look in the Apollo cache, it's been created using the keyField names and the values in an object, such as
HistoricalData:{"variable":"GAS.TOTAL","workspace":"ABC"}
instead of
HistoricalData:GAS.TOTAL:ABC
so when I try to readFragment it returns null
client.readFragment({
id: `HistoricalData:${props.variable}:${props.workspace}`,
fragment: apolloGQL`fragment MyHistorical on Historical {
variable
workspace
}`})
It does actually return a value from the cache if I create my id in the structure that exists in the cache and readFragment using this.
Has anyone else noticed that Apollo client is not creating the cache id's in the structure that they describe in the docs?
After some research I came upon the correct way to handle this case. I know that you have already moved on, but just in case anyone else has the same problem in the future, here goes:
As described in the documentation for customizing the cache ID, the cache ID will be an stringified object, as you pointed out. It's not quite explicit in the documentation, but at this point in time it provides this nested example for a cache ID:
Book:{"title":"Fahrenheit 451","author":{"name":"Ray Bradbury"}}
But as users we don't have to preoccupy us with the format of this ID, because there's a helper for that, called cache.identify.
For your specific case, you could use something like this:
const identifiedId = cache.identify({
__typename: 'HistoricalData',
variable: 'GAS.TOTAL',
workspace: 'ABC'
});
cache.readFragment({
id: identifiedId,
fragment: apolloGQL`fragment MyHistorical on Historical {
variable
workspace
}`
});
I have to order the search results from solr based on some fields which are already indexed.
My current api request is like this without sorting.
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19
And it gives the search results based on the indexed order. But I have to reorder this results based on the filed 'last_login' which is already indexed DateTimeField.
Here is my viewset
class ProfileSearchView(FacetMixin, HaystackViewSet):
index_models = [Profile]
serializer_class = ProfileSearchSerializer
pagination_class = PageNumberPagination
facet_serializer_class = ProfileFacetSerializer
filter_backends = [HaystackFilter]
facet_filter_backends = [HaystackFilter, HaystackFacetFilter]
def get_queryset(self, index_models=None):
if not index_models:
index_models = []
queryset = super(ProfileSearchView, self).get_queryset(index_models)
queryset = queryset.order_by('-created_at')
return queryset`
Here I have changed the default search order by 'created_at' value. But for the next request I have order based on the 'last_login' value. I have added a new parameter in my request like this
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19&sort='last_login'
but it gives me an error
SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field sort]
How can I achieve this ordering possible? Please help me with a solution.
The URL you provided http://127.0.0.1:8000/api/v1/search/facets/ is not direct SOLR URL. It must be your middle-ware. Since you have tried the query directly against Solr and it works, the problem must be somewhere in middle-ware layer.
Try to print or monitor or check logs to see what URL the midde-ware actually generates and compare it to the valid URL you know works.
I am trying to save Event. But it does not work. Will you please help? thanks alot
query = []
query = Identity.all().filter('name =', 'k').fetch(1)
if query:
for q in query:
event_id = q.key().id()
Event(description=description, identity=event_id)
Event Model
class Event(search.SearchableModel):
description = db.TextProperty(required=True)
identity = db.ReferenceProperty(Identity)
Getting error message >
if value is not None and not value.has_key():
AttributeError: 'long' object has no attribute 'has_key'
Your assigning the id of the object into a ReferenceProeprty, this is wrong.
Your code should look something like this:
query = Identity.all().filter('name =', 'k').get()
if query:
Event(description=description, identity=q)
Also instead of having your own name attribute you use use the buitin key_name attribute that each Model has, its faster and cheaper.
query = Identity.get_by_key_name(k)
if query:
Event(description=description, identity=q)