I want to make a query to get the number of rows in the model MyTable that have the field expire (datetime) be a date in the current week.
In MySQL I execute the following query:
select count(expire) from MyTable where yearweek(expire) = yearweek(now());
So I can get the rows that belongs to the current week starting from Sunday. I tried replicate that using queryset in my view like this:
now = datetime.now()
myquery = MyTable.objects.filter(expire__year=now.year).filter(expire__week=now.isocalendar()[1])
But the thing is, Django method of querying starts from Monday, I want it for Sunday. So I though in doing a raw sql query Like this:
myquery = MyTabel.objects.raw('select count(expire) from MyTable where yearweek(expire) = yearweek(now());')
But it doesnt work, it doesnt output a value. How can I make this query?
I'm using mysql 5.7, python 3.7 and django 2.1.11
I know these are all old versions but I can't update.
Related
I have a requirement to fetch the data (both i_week and i_year) for the last one year from current date. The table has the following columns. Let us call the table as temp.
i_week - The week number [1,52]
i_year - The year
Other columns
I know how to fetch the data using SQL (Postgres). This is the query:
SELECT "i_week", "i_year" FROM "temp" WHERE ("i_week", "i_year") BETWEEN (1, 2021) AND (52, 2022);
What I have tried so far using Django ORM is this:
temp.objects.filter(i_week__range=(previous_week, current_week), i_year__range=(previous_year, current_year))
But this is not giving me the desired result.
How can I achieve the above SQL query using Django ORM ? How can I filter the ranges of i_week and i_year at once in ORM ?
let's just mention the Q object method. You can try the ORM query this way:
from django.db.models import Q
temp.objects.filter(
Q(i_week__range=(previous_week, current_week)) &
Q(i_year__range=(previous_year, current_year))
)
I'm querying the latest entry from a table like this:
data = dbsession.query(db.mytable).order_by(db.mytable.timestamp.desc()).with_entities(db.mytable.timestamp).first()
On startup this is fine, but if new etries are added by the same dbsession during runtime, the query above doesn't recognize them.
But the following code without SQLAlchemy works as expected:
sql_query="SELECT timestamp FROM mytable ORDER BY timestamp DESC LIMIT 1"
data = cursor.execute(sql_query)
How do I get SQLAlchemy to work in this case?
Had a similar issue once, without recalling exactly why sqlAlchemy behaves this way, you need to commit the session before the select to refresh the data:
session.commit()
I'm struggling on how to create an SQL query using SQLite 3 in Python. I have created a sql table with data added. I think I've set the table data type for registration date to date. When I try to search registrations over a year old I get different errors, dependent on what I search.
The statement I am using is:
Cursor = conn.execute("select * from members where MEMBERSHIP_DATE <= DateAdd(1 , GetDate() )")
The error I get is:
File "*****", line 99, in searchregistration
cursor = conn.execute("select * from members where REGISTRATION_DATE <= DateAdd(1 , GetDate() )")
sqlite3.OperationalError: no such function: DateAdd
What is the best way to query my table in order to find registrations older than a year?
The format I have dates in the table is dd/mm/yyyy
Any help or advise is greatly appreciated. This is my first foray into SQLite
The correct syntax of MySQL DATE_ADD() is :
select * from members
where MEMBERSHIP_DATE <= DATE_ADD(GETDATE(), INTERVAL 10 DAY)
If you are using SQLite like mentioned in the title, then use this:
select * from members
where MEMBERSHIP_DATE <= DATE('now', '+1 day')
SELECT *
FROM Residents
WHERE apartment_id IN (SELECT ID
FROM Apartments
WHERE postcode = 2000)
I'm using sqlalchemy and am trying to execute the above query. I haven't been able to execute it as raw SQL using db.engine.execute(sql) since it complains that my relations doesn't exist... But I succesfully query my database using this format: session.Query(Residents).filter_by(???).
I cant not figure out how to build my wanted query with this format, though.
You can create subquery with subquery method
subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).filter(Residents.apartment_id.in_(subquery))
I just wanted to add, that if you are using this method to update your DB, make sure you add the synchronize_session='fetch' kwarg. So it will look something like:
subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).\
filter(Residents.apartment_id.in_(subquery)).\
update({"key": value}, synchronize_session='fetch')
Otherwise you will run into issues.
My Django-foo isn't quite up to par to translate certain raw sql into the ORM.
Currently I am executing:
SELECT avg(<value_to_be_averaged>), <id_to group_on>
FROM <table_name>
WHERE start_time >= <timestamp>
GROUP BY <id_to group_on>;
In Django I can do:
Model.objects.filter(start_time__gte=<timestamp>).aggregate(Avg('<value_to_be_averaged>'))
but that is for all objects in the query and doesn't return a query set that is grouped by the id like in the raw SQL above. I've been fiddling with .annotate() but haven't made much progress. Any help would be appreciated!