Django startswith query - python

How would I do the following query?
SELECT * FROM title WHERE id LIKE '12345%'
What I currently have is:
Title.objects.get(id='12345')
Which obviously doesn't do the LIKE% (and the icontains does both). What would be the correct query here?

Title.objects.filter(id__startswith='12345')
https://docs.djangoproject.com/en/dev/ref/models/querysets/

You can do like this where code would be your startswith string by which you want to filter the table.
code = '12345'
enter code hereTitle.objects.extra(where=["%s LIKE id||'%%'"], params=[code])

Related

How can I use LIKE operation on a parameter? [duplicate]

I've got an argument tag and I perfomed this way:
cursor.execute("SELECT * FROM posts WHERE tags LIKE '%?%'", (tag,))
but it doesn't seem to work.
I'm new to sqlite, please tell me how to fix it. Thx !
Apply the wildcards to the parameter, not the SQL:
cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (f'%{tag}%',))
The ? SQL parameter interpolation adds quoting for you, so your query ends up as '%'value'%', which is not valid SQL.
Remove the %:
cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (tag,))
This should format it as you wanted. For example, if tag == 'test' the full query would be:
SELECT * FROM posts WHERE tags LIKE 'test'

Django filter has_key generates wrong SQL

I need to filter some objects that have no specific value in the field. I tried to do it like this:
MyModel.objects\
.filter(<some filters>)\
.exclude(json_field__has_key='some_field', json_field__some_field=True)
But this code generates wrong SQL query:
...
AND NOT (
"my_model"."json_field" ? some_field AND
("my_model"."json_field" -> 'some_field') = 'true' AND
"my_model"."json_field" IS NOT NULL)
)
...
On the first line some_field used without qoutes. I fixed it by adding single qoutes to the string like this: json_field__has_key="'some_field'" but I dont think it's a good solution.
Does anyone have an idea why it works this way and how I should fix it?
Well, my bad...
I just logged my queries as queryset.query that has really wrong representation of the SQL query. When I logged real queries using connector I saw correct query (see this answer for more details).

Queries with LIKE (sql) equivalent in Python and string description

I want to make a query in python using the equivalent of LIKE in sql.
So for I've been using the __contains option like this :
results = objectName.objects.filter(variable__contains='someword')
But now I want to put a constraint on the variable like :
filter(variable__contains='_A%')
with "_" being any character and "%" all character it wants - like in SQL - but it doesn't work :(
Does someone know how to do this ?
Django's queries don't seem to support LIKE out of the box (which is kind of weird).
You can translate your LIKE expression to a regular expression and use __regex:
.filter(variable__regex='.A.*')
(Another, more advanced way would be to write the LIKE lookup class yourself and register it on CharField.)

How to query mongoDB using Mongoengine with several "WHERE" arguments (what is AND)?

I'm currently querying a MongoDB with the following mongoengine query:
queryResults = Event.objects(title__icontains=q)
This works well, but I want to add another argument so it becomes something like this:
queryResults = Event.objects(title__icontains=q and end__gte=datetime.utcnow())
Unfortunately, simply using and doesn't work here. I tried other things like & and &&, but to no avail. I also checked the mongoengine docs, but I can't find anything about it.
Would anybody have any idea how I could do this? All tips are welcome!
Try putting a "," between this:
queryResults = Event.objects(title__icontains=q, end__gte=datetime.utcnow())

Sqlalchemy get last X rows in order

I need to get the last X rows from a table, but in order of the ID. How could I achieve this?
query = users.select().order_by(users.c.id.desc()).limit(5)
print reversed(conn.execute(query).fetchall() )
something like that anyway
This worked for me...
c=session.query(a).order_by(a.id.desc()).limit(2)
c=c[::-1]
This solution is 10 times faster than the python slicing solution proposed by BrendanSimon.
I believe you can prefix the order_by parameter with a '-' to get reverse order.
query = users.select().order_by(-users.c.id.desc()).limit(5)
Also, I believe you can use python slices as an alternative to limit.
query = users.select().order_by(users.c.id.desc())[-5:]
query = users.select().order_by(-users.c.id.desc())[:5]

Categories