Preventing select query on ForeignKey when the primary key is known - python

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.

Related

Python, SQLAlchemy, Snowflake, existing column defaults - insert in existing table with an autoincrement or column default value

I have an existing table in Snowflake and I'd like to use SQLAlchemy to insert records into. This table has an autoincrement ID field and two timestamp fields that have a default value of CURRENT_TIMESTAMP(). I'm mostly concerned with the autoincrementing ID field (the timestamps I can calculate and populate before inserting).
Reading around I see that there is generally a bit of a challenge getting autoincrement fields to be populated - the Snowflake documentation seems to avoid the subject of working with existing tables, and refers us to the method of specifying a Sequence in the model:
From https://docs.snowflake.com/en/user-guide/sqlalchemy.html#auto-increment-behavior:
Auto-increment Behavior
Auto-incrementing a value requires the Sequence object. Include the
Sequence object in the primary key column to automatically increment
the value as each new record is inserted. For example:
t = Table('mytable', metadata,
Column('id', Integer, Sequence('id_seq'), primary_key=True),
Column(...), ...
)
This doesn't help if the table already exists and ID is AUTOINCREMENT, however. Also creating a new sequence object for every autoincrementing ID field in the database feels a little heavy handed seeing as Snowflake should handle this nicely within the table.
My question really is:
Have you managed to use SQLAlchemy to insert records into an existing Snowflake table and get an existing AUTOINCREMENT or IDENTITY START 1 INCREMENT 1 type of field to update? If so, how?
Do I have to create my tables in code through SQLAlchemy using a model (and using a Sequence for the ID field) if I then wish to be able to insert records into it using SQLAlchemy?
Thanks in advance for any thoughts/answers on this.
I don't use snowflake but it seems from the docs that autoincrement actually uses a sequence anyways: optional-parameters, scroll to AUTOINCREMENT.
So maybe a sequence already exists anyways? Can you inspect/describe the table with some sort of commandline utility?
I use postgresql and I actually make sequences and then add them to the table so it doesn't seem that weird to me, postgresql's autoincrement also uses sequences implicitly anyways -- DATATYPE-SERIAL
I think you should be able to just insert without specifying an id and it will autoincrement the sequence either way. Or add an object without an id to the session to commit.

Check data exist in any foreign key table of pk table in MySQL database using django python

I am trying to check if there has any data in all referenced table of a primary key table. Is it possible in mysql using django, not any raw query, need to do it in django, python.
Find 02 queries in mysql, but need more details in django.
SELECT \* FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
SELECT DISTINCT KEY_COLUMN_USAGE.CONSTRAINT_NAME,
KEY_COLUMN_USAGE.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME,
KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME,
KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE
ON TABLE_CONSTRAINTS.CONSTRAINT_NAME=KEY_COLUMN_USAGE.CONSTRAINT_NAME
WHERE TABLE_CONSTRAINTS.CONSTRAINT_TYPE="FOREIGN KEY"
AND TABLE_CONSTRAINTS.CONSTRAINT*SCHEMA=\<DATABASE*NAME\>;
Thanks in advance!
I tried to get all referenced foreign key table of a primary key table. Then check if any data exists in those foreign key tables. But I am not getting any source in django. Is ist possible?

How to retrieve all data from foreign keys with Django ORM and return them as JsonResponse

I am trying to get all the data from a model and its foreign keys and I have a hard time using select_related() and values() or values_list().
I got an Order table who got two foreign keys. I need to query all the data and send it as a JsonResponse. This is the line:
Order.objects.select_related('persoana_fizica__persoana_juridica').values()
I saw I can write inside values what fields I need, I am looking for a method to select all of them without writing every single one, 'all' didn't worked. Any ideas?

are web2py Database Abstraction Layer (DAL) references on cascade by default?

When I create a database in web2py using the DAL, and I create a table for the user comments on my website for example and I need to be able to get the user that sent that particular comment, I can do it by email..
However emails can change over time (possible option) and the database itself could end up looking for a non existent user if the email is not updated on all "child" tables that uses that email as reference 1 to 1 for that user.
For this reasons, I would need to automatically update all the Foreign Keys in child tables, so is this feature (update on cascade on foreign keys) present and by default when using DAL / is it possible to tell the DAL connection to do it by adding a updateoncascade=True in needed Field("name", type="type", notnull=True, updateoncascade=True) fields?
The DAL does not provide an API to specify ON UPDATE CASCADE when creating a table, so you would have to do that externally. Alternatively, you could make use of the _after_update hook to update records in any child tables.
Also consider whether you want to set a foreign key on the email address rather than using the built-in reference field functionality, which creates a foreign key on the id field of the parent table. Because the id of a given user record will never change, you do not have to worry about cascading updates:
db.define_table('comments',
...,
Field('author', 'reference auth_user'))
Above, 'reference auth_user' sets up a foreign key to the db.auth_user.id field.

set Django RawQuerySet to do not defer attributes

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')

Categories