Update Query with SQLAlchemy with condition [duplicate] - python

UserTable is:
id (INT)
name (STR)
last_login (DATETIME)
Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.
It seems to me that there are 2 ways:
issue a direct SQL using db_engine (losing the mapper)
OR query the user first and then update the object
Both work fine but look quite disgusting in code.
Is anyone aware of a more elegant way of doing an update-with-no-query using sqlalchemy? Is there another ORM who has got this right?
Thanks

Assuming you have a mapper UserTable in place:
DBSession.query(UserTable).filter_by(id = user_id).\
update({"last_login":datetime.datetime.now()}, synchronize_session=False)
Additional parameters in the docs.

Related

How to do select with where on second order ForeignKeyField in Python Peewee ORM?

I'm using the (awesome) Peewee ORM for my database needs and I now constructed a query as follows:
OauthCI.select().where(OauthCI.oauth.user.id == 2)
So OauthCI has a ForeignKeyField called oauth, which points to a table which in turn has a ForeignKeyField which is called user. Unfortunately, this gives me an error saying: AttributeError: 'ForeignKeyField' object has no attribute 'user'.
Does anybody know how I can select all records from OauthCI which has a oauth with a user with an id of 2? All tips are welcome!
Your intuition is good but unfortunately peewee does not work that way right now. Here is how you do it instead:
OauthCI.select().join(Oauth).join(User).where(User.id == 2)

SQLAlchemy: limit in the same string as where

We're trying to enable a SQL query front-end to our Web application, which is WSGI and uses Python, with SQLAlchemy (core, not ORM) to query a PostgreSQL database. We have several data layer functions set up to assist in query construction, and we are now trying to set something up that allows this type of query:
select id from <table_name> where ... limit ...
In the front end, we have a text box which lets the user type in the where clause and the limit clause, so that the data can be queried flexibly and dynamically from the front end, that is, we want to enable ad hoc querying. So, the only thing that we now firsthand is:
select id from <table_name>
And the user will type in, for example:
where date > <some_date>
where location is not null limit 10 order by location desc
using the same back end function. The select, column and table should be managed by the data layer (i.e. it knows what they are, and the user should not need to know that). However, I'm not aware of any way to get SQLAlchemy to automatically parse both the where clause and the limit clause automatically. What we have right now is a function which can return the table name and the name of the id column, and then use that to create a text query, which is passed to SQLAlchemy, as the input to a text() call.
Is there any way I can do this with SQLAlchemy, or some other library? Or is there a better pattern of which I should be aware, which does not involve parsing the SQL while still allowing this functionality from the front-end?
Thanks a lot! All suggestions will be greatly appreciated.
I'm not sure I follow, but the general SQL-Alchemy usage is like:
results = db.session.query(User).filter(User.name == "Bob").order_by(User.age.desc()).limit(10)
That will query the User table to return the top ten oldest members named "Bob"

Django: Is it possible to achieve the same thing as sql's exists?

To make my question more understandable, here's an example.
There are two models:
class A(models.Model):
name = models.CharField(max_length = 10)
class B(models.Model):
a = models.ForeignKey(A)
name = models.CharField(max_length = 10)
So in this example, A and B are of one-to-many relationship. Now let's say I'd like to make the following query: find an A that has at least one B as child. In sql, clearly I should use exists clause. Is it possible to achieve exactly the same with orm?
I've done some research on that but can't find a perfect match to the sql query. The closest solution is like:
A.objects.filter(b__pk__gt = 0).distinct()
But it's still far from the exists clause in sql and might not be as efficient as exists.
The following will select all As that have one or more associated Bs:
A.objects.filter(b__isnull=False)
Switching it to b__isnull=True will select only As that have no Bs associated with them.
Actually (if I am not misunderstood what you are trying to do) with plain sql a simple left join would be the way to go instead of the EXISTING clause.
Your queryset works just fine without the .distinct()
I recomend you to have a look at the queries that django orm generates, so that you can see what's going on and actually run ANALYZE/EXPLAIN instead of guessing the performances.
You can see the raw query from the query attribute of a queryset or, even better, install the django debug toolbar and see all the queries for a given request.

Convert SQL query to Django friendly format for application

I have an SQL query thats runs on the Postgres database of my Django based webapp. The query runs against the data stored by Django-Notifications (a reusable app) and returns a list of email addresses that have not opted out of a specific notice type.
What I would really like to be able to do is to build an application that does this on demand, so I'm looking for an example of how to convert the SQL so it can run inside a Django view that will pass out a formatted email list. The SQL is currently thus:
gr_webapp=# select email from emailconfirmation_emailaddress where verified and user_id not in
(select user_id from notification_noticesetting s join notification_noticetype t on s.notice_type_id = t.id
where t.label = 'announcement' and not s.send);
You might have to make appropriate adjustments as far as model names go, since you didn't show them in your question:
users_to_exclude = Noticesetting.objects.filter(send=False, notice_type__label='announcement').values('user')
emails = Emailaddress.objects.exclude(user__in=users_to_exclude)

simple update in sqlalchemy

UserTable is:
id (INT)
name (STR)
last_login (DATETIME)
Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.
It seems to me that there are 2 ways:
issue a direct SQL using db_engine (losing the mapper)
OR query the user first and then update the object
Both work fine but look quite disgusting in code.
Is anyone aware of a more elegant way of doing an update-with-no-query using sqlalchemy? Is there another ORM who has got this right?
Thanks
Assuming you have a mapper UserTable in place:
DBSession.query(UserTable).filter_by(id = user_id).\
update({"last_login":datetime.datetime.now()}, synchronize_session=False)
Additional parameters in the docs.

Categories

Resources