I have API - python script (using Flask and SQLite) which works with database with 3 tables.
Table Comany has relationship 1:N with table User. And table Company has relationshipt 1:N with table Keyword.
Now, if I will delete some company, I expect it will also delete all users who belong to company, as well as all keywords.
I have found, I have to turn on FOREIGN Keys, using these lines
#event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
if type(dbapi_connection) is sqlite3.Connection: # play well with other DB backends
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
However it will still only delete company, and foregin keys in rows of users as well as keywords of this company stay NULL.
E.g. Table User
ID, Name, Pass, FK_company_name
These are lines how I am deleting company
...
company_id = request.args.get('company_id')
company = Company.query.get(company_id)
db.session.delete(company)
db.session.commit()
...
Do I have to set something else?
So I have a file called create_tables.py with the following code:
import sqlite3
connection = sqlite3.connect("mydata.db")
cursor = connection.cursor()
create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)"
cursor.execute(create_table)
create_table = "CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name text, price real)"
cursor.execute(create_table)
connection.commit()
connection.close()
When trying to make a GET request via postman I am provided this error:
sqlite3.OperationalError: no such table: items
But there is a table that has been created called item_model.
I didn't specify the creation of this table. I am wondering why my items table is not being created but this item_model table was.
I am trying to create a social network using flask and sqlite3. I had created almost all the main things like post, edit post, delete post. But I also want to add the like button for every post. I had created like number(How many like this post got) and like button and it is working fine but If you like my post for the first time and again login your account then you can again like that post which you had already liked by your account.
I had an idea to save who liked my post but i don't know how to implement that exact code in my webapp.I am using sqlite3 so I am not finding any solution for this issue. I had found exactly same question for mysql or any other database but I had not for sqlite3.
Ok here is my idea,
I had already mentioned that I am using sqlite3 so I had created table like this:
conn=sqlite3.connect('data/detailpost.db')
c=conn.cursor()
c.execute("""CREATE TABLE postdetail(
name text,
address text,
post text,
post_date text,
secretcode text,
mainname text,
likes integer,
likers text)""")
conn.commit()
conn.close()
and If someone click like button(In template) then that will come in this part of back-end where I am getting liker mainname and oid number of that post.And this is the same back-end code which increase the like of the post. Like this
#app.route('/social/post/like',methods=['POST'])
def likedofsocial():
if request.method=='POST':
oid=request.form['oid']
mainusernameofliker=request.form['username']
conn=sqlite3.connect('data/detailpost.db')
c=conn.cursor()
c.execute("SELECT *,oid FROM postdetail WHERE oid="+oid)
alldata=c.fetchall()
for rec in alldata:
c.execute("""UPDATE postdetail SET
name=:name,
address=:address,
post=:post,
post_date=:datee,
secretcode=:secret,
mainname=:mainname,
likes=:likes
likers=:likers
WHERE oid=:num""",
{
'name':rec[0],
'address':rec[1],
'post':rec[2],
'datee':rec[3],
'secret':rec[4],
'mainname':rec[5],
'likes':(int(rec[6]+1)),
'likers':mainusernameofliker,
'num':oid,
})
conn.commit()
conn.close()
.....
Here in this above part I don't know how to save multiple mainusernameofliker inside likers beacause there will not be only one person who likes my posts.
Now I have only idea for front-end I had not tried any of the code which is mentioned below!! I just think following code could works fine
"For front-end check that likers data and
(% if (your mainusername is in that likers data ) %)
then show already liked(Liked) or disable like button
(% else (your username is not in that likers data) %)
then that show like or make clickable like button".
(% endif %)
Probably, I could get help as soon as possible and any help will be appreciated.
I think your main question is that how to store the multiple users who would like the post. It is very simple, you just need to create one more table maybe called postlikers. This table will reference primary keys of user and postdetail. Basically a many-to-many relationship between user and postdetail tables.
I will show you an example that how you can define the tables below:
import sqlite3
conn=sqlite3.connect('detailpost.db')
c=conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY,
name text)
""")
c.execute("""CREATE TABLE IF NOT EXISTS postdetail(
id INTEGER PRIMARY KEY,
name text,
address text,
post text,
post_date text,
secretcode text,
mainname text,
likes integer DEFAULT 0
)""")
c.execute("""CREATE TABLE IF NOT EXISTS postlikers(
id INTEGER PRIMARY KEY,
post_id INTEGER,
user_id INTEGER,
FOREIGN KEY(post_id) REFERENCES postdetail(id),
FOREIGN KEY(user_id) REFERENCES user(id)
)
""")
conn.commit()
conn.close()
# Add data
user_data = [('Carl'), ('Mel'), ('Bobby')]
post_data = [('first_post', 'whajjne', 'I love everything', 'dfweffwwffefe', 'secret', 'Carl', 0),
('second_post', 'whajjne', 'I love everything', 'dfweffwwffefe', 'secret', 'Mel', 0)]
conn=sqlite3.connect('detailpost.db')
c=conn.cursor()
for user in user_data:
c.execute('INSERT INTO user (name) VALUES (?);', (user,))
for post in post_data:
c.execute('INSERT INTO postdetail (name, address, post, post_date, secretcode, mainname,likes ) VALUES (?,?,?,?,?,?, ?);', post)
conn.commit()
conn.close()
I'm creating a small python program and i use the ORM peewee to manage my Sqlite database. I want to create a table without primary key using peewee. The problem is that peewee is adding a primary key if i dont specify one. After read the docs, i found the parameter without_rowid supposed to prevent peewee to create this primary key. But it doesnt works.
Here is a small example of code :
#!/usr/bin/python
import peewee
import traceback
db_proxy = peewee.Proxy()
class BaseModel(peewee.Model):
class Meta:
database = db_proxy
class table1(BaseModel):
id = peewee.IntegerField(primary_key=True)
field1 = peewee.CharField()
field2 = peewee.IntegerField()
class table2(BaseModel):
table1_id = peewee.IntegerField()
field1 = peewee.CharField()
class Meta:
without_rowid = True
try:
# create database
db = peewee.SqliteDatabase("test.db")
db_proxy.initialize(db)
db.create_tables([table1, table2])
except Exception as e:
traceback.print_exc(e)
Same with the without_rowid, peewee automatically add an id primary key to my table2 table. Here is the schema of the created database :
CREATE TABLE IF NOT EXISTS "table1"(
"id" INTEGER NOT NULL PRIMARY KEY,
"field1" VARCHAR(255) NOT NULL,
"field2" INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS "table2"(
"id" INTEGER NOT NULL PRIMARY KEY,
"table1_id" INTEGER NOT NULL,
"field1" VARCHAR(255) NOT NULL
) WITHOUT ROWID;
Do you know a way to solve this problem and permit me to create a table without rowid ?
ps : if you're asking why i want to create a table without primary key, it's because i need to insert data from a csv file. (sqlite3 database.db ".mode csv" ".import file.csv table1"). As i have an AUTO INCREMENT PRIAMRY KEY on my table, i need to trick a little bit by importing the csv file in a temporary table without primary key as explained here : http://objectiveme.com/populating-a-sqlite-database-using-csv/
Thx ! :)
Peewee documentation is also VERY CLEAR about how to disable primary key:
http://docs.peewee-orm.com/en/latest/peewee/models.html#models-without-a-primary-key
Please READ THE DOCS.
To create a Peewee model without a primary key (which is distinctly different from "WITHOUT ROWID"), you can specify "primary_key = False":
class NoPKModel(Model):
key = TextField()
data = TextField()
class Meta:
primary_key = False
This will not automatically create an "id" field.
Without ROWID is a SQLite optimization with rather specific use-case. Please read the SQLite documentation and understand the SQLite data-model before using it: https://www.sqlite.org/rowidtable.html
I have a database schema file which I read in my Flask module.
PRAGMA foreign_keys = 1;
drop table if exists user;
create table user(uid integer primary key autoincrement,
username text not null,
password text not null,
email text not null);
drop table if exists asset;
create table asset(aid integer primary key autoincrement,
assetname text not null,
releasedate text,
FOREIGN_KEY(owner) REFERENCES user);
When I remove the foreign key field, it works fine.
Error trace:
File "main.py", line 75, in <module>
create_table()
File "main.py", line 30, in create_table
conn.cursor().executescript(f.read())
sqlite3.OperationalError: near "(": syntax error
I can post the method which uses this script but I don't think the problem lies there.
As #soon pointed you have a syntax error on FOREIGN KEY keyword, also you should define column name (owner).
drop table if exists asset;
create table asset(aid integer primary key autoincrement,
assetname text not null,
releasedate text,
owner integer,
FOREIGN KEY(owner) REFERENCES user);
You should replace the underscore between the FOREIGN and KEY with a space. The following diagrams shows the constraint syntax:
And the foreign-key-clause syntax is: