I have two models, one with ForeignKey I'm trying to match. In order to do so, I'm looking up second model by a specific number and a date. The problem is it has two dates and I have to make decision on which date to choose. Under some circumstances it is set to NULL, in some it is not. If it is I have to get the second date field. I have something like this:
class MyModel1(models.Model):
model2_key = models.ForeignKey(MyModel2)
model1_date=...
model1_number=...
second model:
class MyModel2(models.Model):
model2_date1=...
model2_date2=...
model2_number=...
Now, how to make the choice? I have looked up documentation regarding F expressions, Q expressions, When expressions, Select and I'm a little bit confused. How can I wrtie a function that returns searched MyModel2 object? I have something like this, but it won't work.
def _find_model2(searched_date, searched_number):
searched_model2=MyModel2.objects.get(Q(model2_number=searched_number),
Q(When(model2_date1__e='NULL', then=model2_date2) |
Q(When(model2_date1__ne='NULL', then=model2_date1))=searched_date))
I am quite new to django, so any help will be appreciated.
I have made a workaround this issue, I don't think it's mostefficient and elegant one, but it works. Should anyone have a better solution please post it.
First, all objects whose corresponding dates match are called:
from_query = list(MyModel2.objects.filter(Q(model2_date1__range=
(datetime_min, datetime_max)) | Q(model2_date2__range=(datetime_min, datetime_max)),
model2_number=searched_number))
Then I iterate over found objects:
to_return = []
for item in from_query:
if item.model2_date1:
to_return.append(item)
elif datetime_min <= item.model2_date2 <= datetime_max:
to_return.append(item)
EDIT: I've come up with a solution. Assuring that model2_date1__isnull=True is enough. The solution now looks like this:
from_query = list(MyModel2.objects.get((Q(model2_date1__range=(datetime_min, datetime_max)) |
Q(Q(model2_date2__range=(datetime_min, datetime_max)),
Q(model2_date1__isnull=True)),
model2_number=searched_number))
Related
Consider this simple django model (backed by Postgres):
class M(Model):
a = BooleanField(default=False)
b = BooleanField(default=False)
c = BooleanField(default=False)
class Meta:
app_label = 'my_app'
How can I use update to set the value of c to the logical AND of a and b? My first instinct was
M.objects.update(c=F('a') and F('b'))
but apparently the python is executed first (with the logical AND of the F functions simply returning the second method), because this yields the following SQL:
UPDATE "my_app_m"
SET "c" = "my_app_m"."b"
I tried wrapping the expression in ExpressionWrapper, but this had no effect. I also tried using * instead of and (to multiply the F expressions), but this yielded an operation error on the sql side.
I know I could do this in python by fetching the objects, manipulating them, and then saving. I'm guessing I could also probably do the update by casting to int then multiplying, then casting back. But I'm surprised the ORM doesn't simply handle this. Is there a step I'm missing, or a different standard way of accomplishing the same effect?
Thanks for your time!
After poking around a bit, I found this solution. Not a huge fan of answering my own questions, but this was vexing me so maybe it will help someone else. I'm not sure if it's the best or most direct solution, so hopefully someone else will come up with a better answer and I can accept that.
What I have right now:
M.objects.update(
c=Case(
When(a=True, b=True, then=Value(True)),
default=Value(False)
)
)
Another alternative. Guess this should have been obvious given the nature of this specific problem, but it never occurs to me to opt for more queries:
M.objects.update(c=False)
M.objects.filter(a=True, b=True).update(c=True)
You can make use of a Q object here:
from django.db.models import Q
M.objects.update(c=Q(a=True, b=True))
In PostgreSQL, this will result in a query:
UPDATE "my_app_m"
SET "c" = ("my_app_m"."a" = true AND "my_app_m"."b" = true)
I have a app that lets the user search a database of +/- 100,000 documents for keywords / sentences.
I am using Django 1.11 and the Postgres FullTextSearch features described in the documentation
However, I am running into the following problem and I was wondering if someone knows a solution:
I want to create a SearchQuery object for each word in the supplied queryset like so:
query typed in by the user in the input field: ['term1' , 'term2', 'term3']
query = SearchQuery('term1') | SearchQuery('term2') | SearchQuery('term3')
vector = SearchVector('text')
Document.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank').annotate(similarity=TrigramSimilarity(vector, query).filter(simularity__gt=0.3).order_by('-simularity')
The problem is that I used 3 terms for my query in the example, but I want that number to be dynamic. A user could also supply 1, or 10 terms, but I do not know how to add the relevant code to the query assignment.
I briefly thought about having the program write something like this to an empty document:
for query in terms:
file.write(' | (SearchQuery( %s )' % query ))
But having a python program writing python code seems like a very convoluted solution. Does anyone know a better way to achieve this?
Ive never used it, but to do a dynamic query you can just loop and add.
compound_statement = SearchQuery(list_of_words[0])
for term in list_of_words[1:]:
compound_statement = compound_statement | SearchQuery(term)
But the documentation tells us that
By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms.
are you sure you need this?
let's say that I have an Address model with a postcode field. I can lookup addresses with postcode starting with "123" with this line:
Address.objects.filter(postcode__startswith="123")
Now, I need to do this search the "other way around". I have an Address model with a postcode_prefix field, and I need to retrieve all the addresses for which postcode_prefix is a prefix of a given code, like "12345". So if in my db I had 2 addresses with postcode_prefix = "123" and "234", only the first one would be returned.
Something like:
Address.objects.filter("12345".startswith(postcode_prefix))
The problem is that this doesn't work.
The only solution I can come up with is to perform a filter on the first char, like:
Address.objects.filter(postcode_prefix__startswith="12345"[0])
and then, when I get the results, make a list comprehension that filters them properly, like this:
results = [r for r in results if "12345".startswith(r.postcode_prefix)]
Is there a better way to do it in django?
Edit: This does not answer the original question but how to word a query the other way around.
I think what you are trying to do with your "something like" line is properly written as this:
Address.objects.filter(postcode__startswith=postcode_prefix)
In SQL terms, what you want to achieve reads like ('12345' is the postcode you are searching for):
SELECT *
FROM address
WHERE '12345' LIKE postcode_prefix||'%'
This is not really a standard query and I do not see any possibility to achieve this in Django using only get()/filter().
However, Django offers a way to provide additional SQL clauses with extra():
postcode = '12345'
Address.objects.extra(where=["%s LIKE postcode_prefix||'%%'"], params=[postcode])
Please see the Django documentation on extra() for further reference. Also note that the extra contains pure SQL, so you need to make sure that the clause is valid for your database.
Hope this works for you.
Bit of a mouthful but you can do this by annotating your search value and then filtering against it. All happens pretty quickly in-database.
from django.db.models import Value as V, F, CharField
Address.objects.exclude(
postcode_prefix=''
).annotate(
postcode=Value('12345', output_field=CharField())
).filter(
postcode__startswith=F('postcode_prefix')
)
The exclude is only necessary if postcode_prefix can be empty. This would result in an SQL like '%', which would match every postcode.
I'm sure you could do this via a nice templated function these days too... But this is clean enough for me.
A possible alternative. (Have no idea how it compares to the accepted solution with a column as the second param to like, in execution time)
q=reduce(lambda a,b:a|b, [Q(postcode__startswith=postcode[:i+1]) for i in range(len(postcode))])
Thus, you generate all prefixes, and or them together...
The raw SQL query that would do that you need looks something like this:
select * from postal_code_table where '1234567' like postal_code||'%'
This query will select any postal_code from your table that is a substring of '1234567' and also must start from begining, ie: '123', '1234', etc.
Now to implement this in Django, the preferred method is using a custom look up:
from django.db.models.fields import Field
from django.db.models import Lookup
#Field.register_lookup
class LowerStartswithContainedBy(Lookup):
'''Postgres LIKE query statement'''
lookup_name = 'istartswithcontainedby'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return f"LOWER({rhs}) LIKE LOWER({lhs}) || '%%'", params
Now you can write a django query such as the following:
PostCode.objects.filter(code__istartswithcontainedby='1234567')
Similarly, if you are just looking for substring and do not require the startswith condition, simply modify the return line of as_sql method to the following:
return f"LOWER({rhs}) LIKE '%%' || LOWER({lhs}) || '%%'", params
For more detailed explanation, see my git gist Django custom lookup
A. If not the issue https://code.djangoproject.com/ticket/13363,
you could do this:
queryset.extra(select={'myconst': "'this superstring is myconst value'"}).filter(myconst__contains=F('myfield'))
Maybe, they will fix an issue and it can work.
B. If not the issue 16731 (sorry not providing full url, not enough rep, see another ticket above) you could filter by fields that added with '.annotate', with creation of custom aggreation function, like here:
http://coder.cl/2011/09/custom-aggregates-on-django/
C. Last and successful. I have managed to do this using monkeypatching of the following:
django.db.models.sql.Query.query_terms
django.db.models.fields.Field.get_prep_lookup
django.db.models.fields.Field.get_db_prep_lookup
django.db.models.sql.where.WhereNode.make_atom
Just defined custom lookup '_starts', which has reverse logic of '_startswith'
I was wondering if it is possible to do a range search on a MultiValueField. I have a model that looks like the following:
Book
Title = 'Awesome Book'
Prices = [ Decimal('10.00'), Decimal('15.00'), Decimal('20.00') ]
I am indexing the prices field with a MultiValueField and I would like to be able to do the follow:
sqs = SearchQueryResult()
sqs.filter(prices__gt=Decimal('10.00'), prices__lt=Decimal('20.00'))
Is this possible or do I have to use something else to do a range search on multiple values?
Update:
I forgot to mention that the __gt doesn't work and I think it's because it's indexing it as a list of strings. I found the following link where they talk about subclassing MultiValueField. I tried this but I can't get it to give me a list of decimals. The subclassed MultiValueFiled looks like the following:
class MultiValueDecimalField(fields.MultiValueField):
field_type = 'decimal'
One way to solve this problem is doing the following:
sqs.filter(prices__in=['%.2f' % (x/100.00) for x in range(1000, 2000)])
It's very ugly but it works. Still open to other answer though.
Same thing: when I applied filters __gte, __gt etc. I noticed that SearchQuerySet returns incorrect data. When I changed field type to FloatField everything started working right. looks like bug, or smth
Have you tried the range field lookup?
SearchQuerySet().filter(view_count__range=[3, 5])
http://django-haystack.readthedocs.org/en/latest/searchqueryset_api.html#field-lookups
I have some codes like this:
cats = Category.objects.filter(is_featured=True)
for cat in cats:
entries = Entry.objects.filter(score>=10, category=cat).order_by("-pub_date")[:10]
But, the results just show the last item of cats and also have problems with where ">=" in filter. Help me solve these problems. Thanks so much!
You may want to start by reading the django docs on this subject. However, just to get you started, the filter() method is just like any other method, in that it only takes arguments and keyword args, not expressions. So, you can't say foo <= bar, just foo=bar. Django gets around this limitation by allowing keyword names to indicate the relationship to the value you pass in. In your case, you would want to use:
Entry.objects.filter(score__gte=10)
The __gte appended to the field name indicates the comparison to be performed (score >= 10).
Your not appending to entries on each iteration of the for loop, therefore you only get the results of the last category. Try this:
entries = Entry.objects.filter(score__gte=10, category__is_featured=True).order_by("-pub_date")[:10]