set Django RawQuerySet to do not defer attributes - python

According to Django documentation if a field is trying to be reached in raw query set, it would fetch it in real time.
How can I prevent it from fetching fields not being retrieved from the database?
e.g. if I write select name from authors
and later a user will write author.gender it would return None and not attempt to retrieve it from the database?

You could try fetching null for any fields that you do not want to be retrieved, for example:
Person.objects.raw('SELECT id, name, null AS gender from authors')

Related

How to retrieve _id field from document containing both _id and id

I'm trying to query a mongodb collection with documents containing both an _id and and id field (I know this is not an ideal db design, but I don't own the db).
Is there a way to access the _id field using MongoEngine in Flask?
doc['id'] returns the id field and doc['_id'] throws a KeyError.

Is it possible to override "_id" field in MongoDB, when I'm using Django and Mongoengine?

I don't want to create a custom "id" field in MongoDB and make it my primary key.
But I want to override the "_id" field and make it an integer primary key so that every time I post a new document, it should have a integer id rather than ObectID.
Can it be possible by overriding some code in MongoEngine(PyMongo)? or this is the core functionality of MongoDB?
I've tried to insert documents directly in MongoDB database(without using Django), specifying the integer "_id" and it saves the document with no problem. However, when I try to query that particular document then it gives no result.
Same happens with Django, when I hit the API endpoint to see the list of documents it shows the one which has integer id.
But when I try to access that particular one, it says "no result found"
How can I deal with this, please advise.
Note: I'm new to both Django and MongoDB.
When defining a document I used the unique=True attribute on a field to ensure I had such an ID. I'm uncertain if this is your goal.
class Post(Document):
p_id = StringField(min_length=64, max_length=64, required=True, unique=True)
I was using a 64character sha256 hexdigest as the p_id

Saving author of form Web2Py

How can I save & display the name of the user who submits a form saved in a database.
For example:
I have a form that allows users to review products.
I then have a table that lists these reviews.
On the table I want to list each users name besides each review.
You could add a reference field pointing to the db.auth_user table (or whatever table in which you store user data):
db.define_table('review',
...,
Field('reviewer', 'reference auth_user', default=auth.user_id, writable=False),
...)
With the above code, the default value for the "reviewer" field is the ID of the currently logged in user. The field is not writable, so the user has no way to change that (in the review entry form, you might also want to set its readable attribute to False, as there is no need for the author to see it).
Then to display the reviewer name along with the review, you could either do a join or use a recursive select (the former is more efficient if you are displaying many reviews at once, as the recursive select approach requires a separate database query to get each review's author).

Batch Editing in Flask-Admin

I'm using Flask-Admin and I want to be able to update many fields at once from the list view. It seemed like what I'm looking for is a custom action.
I was able to make it work, but I suspect not in the best way. I'm wondering if it could be done more "Flask"-ily.
What I do now, for example if I was updating all rows in table cars to have tires = 4:
A custom action in the CarView class collects the ids of the rows to be modified, a callback url from request.referrer, and the tablename cars, and returns render_template(mass_update_info.html) with these as parameters.
mass_update_info.html is an HTML form where the user specifies 1) the field they would like to change and 2) the value to change it to. On submit, the form makes a POST to a a certain view (do_mass_update) with this data (everything else is passed as hidden fields in this form).
do_mass_update uses the data sent to it to construct a SQL query string -- in its entirety, "UPDATE {} SET {}='{}' WHERE id IN ({})".format(table, column, value, ids) -- which is run via db.engine.execute().
The user is redirected to the callback url.
It bothers me that I don't seem to be using any of SQLAlchemy, but (from a newbie's perspective) it all seems to be based on the model objects e.g. User.query(...), while I only have access to the model/table name as a string. Can I get some kind of identifier from the model, pass that through, and do a lookup to retrieve the on the other side?

Preventing select query on ForeignKey when the primary key is known

to insert a row to a table that has a one-to-one relationship, you would do this in Django:
mypk=2 # Comes from the POST request
model=MyModel(myField="Hello", myForeignModel=ForeignModel.objects.get(pk=mypk))
model.save()
This will cause a SELECT query followed by an INSERT query.
However, the SELECT query isn't really necessary as it will be the mypk that is inserted into the foreign key field. Is there a way to get Django to just insert the primary key without doing a SELECT?
Secondly, are there concurrency issues here (in the event that the primary key would change before the user submits the request). If so, how are these dealt with?
From the docs:
Behind the scenes, Django appends "_id" to the field name to create its database column name.
Simply set myForeignModel_id to the FK value.

Categories