I understand how to create a table and query it using sqlalchemy. But what I am trying to do is different. I just want to query a table that already exists and which I did not create. What that means is I won't have a Python class defined for it in my code.
How do I query such a table ?
You can access an existing table using the following code.
For example if your table is users then:
from sqlalchemy.orm import Session
Base = automap_base()
Base.prepare(engine, reflect=True)
Users = Base.classes.users
session = Session(engine)
res = session.query(Users).first()
Related
I am given a task for a web application I’m developing currently. Currently, my code allow me to do the necessary saving to the existing tables, but I am unsure of how to do the following task. The task is to dynamically create tables as long as the 'save' button is pressed in my web application. I am using SQLite for my database.
Example: I have the field of 'name'. So the user types Test for the name field. Upon saving, this name is stored in an existing table and register under a id of 1. At the same time, I want to be able to create a new table with its own fields. This table will be named example_(id). So in this case it will be example_1.
I’m a beginner in Django and SQL so if anyone can guide/help me in any way, thank you!
Got the error of
views.py
#api_view(['GET'])
def selected_device(request,pk=None):
if pk != None:
devices = Device.objects.filter(pk=pk)
devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)
cursor = connection.cursor()
tablename= "dev_interface_" + str(pk)
cursor.execute(f"SELECT interface FROM {tablename} ")
righttable = cursor.fetchall()
devserializer = DeviceSerializers(devices, many=True)
devdserializer = DeviceDetailSerializers(devicedetail, many=True)
interfaces = []
for i in righttable:
interfaces.append(i[0])
for i in interfaces:
data =[{"interface": i}]
interserializer = InterfaceSerializers(data, many = True)
results = {
"device":devserializer.data,
"device_details" : devdserializer.data,
"interface":interserializer.data,
}
return Response(results)
In interfaces, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26']
I have mentioned in the comments that you can use database connection with raw SQL. Here is an example for you:
from django.db import connection
# Create a connection with your database
cursor = connection.cursor()
# Execute your raw SQL
cursor.execute("CREATE TABLE NameTable(name varchar(255));")
# Create database records
cursor.execute("INSERT INTO NameTable VALUES('ExampleName')")
# Fetch records from the database
cursor.execute("SELECT * FROM NameTable")
# Get the data from the database. fetchall() can be used if you would like to get multiple rows
name = cursor.fetchone()
# Manipulate data
# Don't forget the close database connection
cursor.close()
This is just a basic example about database connection in Django. Customize it depending on your needs. Here is the official documentation for raw SQL and database connections. Also keep in mind that what you are trying to do may not be the best practice or recommended.
We have a relationship table built with the below relationship between models.
https://loopback.io/doc/en/lb3/HasAndBelongsToMany-relations.html
Though we can access the related model via the model instance. I am wondering how we can access the relationship table directly as I want to filter the records from the relationship table's custom field that we have added later in that relationship table.
For an example, after creating a new column (createdat) on AssemblyPart table, I would like to filter the record based on createdat columns.
At the moment, we are using execute method of connector to execute raw sql to access this relationship table.
Use app to access all models individually if they aren't related to User Model:
Reference:
var app = require('../../server/server');
var ModelName = app.models.ModelName;
ModelName.find().then(data=>
{
// Your Data
}).catch(error=>
{
// error
})
I am using mongoDB as my database, i am working on django projects and using mongoengine to connect with database. My question is if my default database in settings.py is DB1 and i want to delete all records of a collection which exists inside DB2 then how can i do this.
settings.py
import mongoengine
mongoengine.connect(
db= "DB1",
host='localhost',
)
models.py
class Resources(Document):
field1= fields.StringField(max_length=20)
field2 = fields.StringField(max_length=70)
field3 = fields.StringField(max_length=70)
field4 = fields.DictField()
meta = {'collection': 'resources', 'allow_inheritance': False, '_target_db': 'DB2'}
python shell
from .models import Resources
import mongoengine
mongoengine.connect('DB2', alias='ces')
ob = Resources()
ob.switch_db('ces')
ob.field1 = value
ob.field2 = value
ob.field3 = value
ob.save()
Now i have collection resources in DB2 and it has some records, i have tried Resources.objects.all().delete() but it is not deleting records form DB2 instead it deletes records from DB1 which is default database.
If each of your model is bound to 1 (and only 1) database, you can achieve what you want using connection alias and meta = {'db_alias': 'your_connectio_alias'} (docs)
See this post for an example
I am used in creating orm and leaving django responsible for creating the tables.But in a project I am involved I have to create a simple CRUD application a frontend for an existing database. The database was created by creating the tables manually. So I have two tables Table1 and Table2 which have a many to many relationship through Tables12. Tables12 looks like the table that django would normaly create using a ManyToManyField thus it has two fields the id's of the two models. So after using django's inspectdb, django successfully created the models according to the SQLite database. The many to many tables like Tables12 was created like the following(as stated above):
class Tables12(models.Model):
table1 = models.ForeignKey(Table1)
table2 = models.ForeignKey(Table2)
class Meta:
managed = False
db_table = "Tables12"
unique_together = (("table1_id", "table2_id"),)
Trying the following gives me an error:
>> table2 = Table2.objects.get(pk=1)
>>tables12 = Tables12.objects.filter(table2=table2)
>>tables12
OperationalError: no such column: Tables12.id
I am guessing Django's orm is expecting an id field in every models created. How can I bypass this behavior? Is there a way to edit the tables so as they look more like django's orm but behave as the existing db's tables? Like:
class Table1(models.Model):
#pre exsiting fields
table2 = models.ManyToManyField(Table2)
or
class Table2(models.Model):
#pre existing fields
table1 = models.ManyToManyField(Table1)
but without destroying database records and without creating tables from start.
You can remove the Tables12 model, and specify the db_table argument to a ManyToManyField:
class Table1(models.Model):
tables2 = models.ManyToManyField(Table2, db_table='Tables12')
You would still not be able to query the Tables12 model directly (it still exists and has an id field), but this would allow you to use the JOINs Django generates for a ManyToManyField:
table1 = Table1.objects.get(pk=1)
tables2 = table1.tables2.all()
This would still not allow you to use Django to write to the join table, but it allows you to use the data that's in it. If at all possible, I'd strongly recommend adding a primary key.
This is what I wanted to do:
I have a table imported from another database. Majority of the columns of one of the tables look something like this: AP1|00:23:69:33:C1:4F and there are a lot of them. I don't think that python will accept them as field names.
I wanted to make an aggregate of them without having to list them as fields in the model. As much as possible I want the aggregation to be triggered from within the Django application, so I don't want to resort to having to create MySQL queries outside the application.
Thanks.
Unless you want to write raw sql, you're going to have to define a model. Since your model fields don't HAVE to be named the same thing as the column they represent, you can give your fields useful names.
class LegacyTable(models.Model):
useful_name = models.IntegerField(db_column="AP1|00:23:69:33:C1:4F")
class Meta:
db_table = "LegacyDbTableThatHurtsMyHead"
managed = False # syncdb does nothing
You may as well do this regardless. As soon as you require the use of another column in your legacy database table, just add another_useful_name to your model, with the db_column set to the column you're interested in.
This has two solid benefits. One, you no longer have to write raw sql. Two, you do not have to define all the fields up front.
The alternative is to define all your fields in raw sql anyway.
Edit:
Legacy Databases describes a method for inspecting existing databases, and generating a models.py file from existing schemas. This may help you by doing all the heavy lifting (nulls, lengths, types, fields). Then you can modify the definition to suit your needs.
python manage.py inspectdb > legacy.py
http://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly
Django allows you to perform raw sql queries. Without more information about your tables that's about all that I can offer.
custom query:
def my_custom_sql():
from django.db import connection, transaction
cursor = connection.cursor()
# Data modifying operation - commit required
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
transaction.commit_unless_managed()
# Data retrieval operation - no commit required
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
acessing other databases:
from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')