return column name from QSqlQuery












0














I am trying to create a small program which should display a tableview based on sqlite table where dates are stored. When a validity is passed the cell shows red to indicate the validity has expired. I have a method "get_date_diff" which retrieves the emails and dates expired and stores them in lists to later use those as variable for mails to be sent in batch i.e: Email(var) has the certificate (var) expired on date (var). My if statement gets me the expired dates and the emails in the listes_pilotes and mail_pilotes i need the third list to be filled with the culprit certificate : was it in column certificate1, certificate2 or possibly both:



def get_date_diff(self):
'''method to retrieve from DB expired certificates '''
query = QSqlQuery("SELECT pilot_1,certificate1,certificate2,pilot_mail FROM Pilots")
liste_pilotes =
mail_pilotes =
#certificate_expired = needs to be filled
append_new = liste_pilotes.append
append_new_mail = mail_pilotes.append
while query_time.next():
pilot_1 = query.value(0)
date1 = query.value(1)
date2 = query.value(2)
pilot_mail = query.value(3)
alter_certif1 = datetime.strptime(date1,"%Y-%m-%d")
alter_certif2 = datetime.strptime(date2,"%Y-%m-%d")
if alter_date1 < datetime.now() or alter_date2 < datetime.now():
append_new(pilot_1)
append_new_mail(pilot_mail)
return liste_pilotes,mail_pilotes


SAMPLE OF THE TABLE



the DB on which the tableview is based:



from PyQt5.QtSql import *

class LmtDataBase():
def __init__(self):
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("LmtPilots.db")

self.db.open()

query = QSqlQuery()
query.exec_('''CREATE TABLE Pilots(id INTEGER PRIMARY KEY,pilot_1 TEXT, datetime1 TEXT, datetime2 TEXT,pilot_mail TEXT)''')

self.db.commit()
self.db.close()

# ...









share|improve this question
























  • Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
    – eyllanesc
    Nov 20 '18 at 20:57










  • Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
    – Heliomaster
    Nov 20 '18 at 21:23












  • In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
    – eyllanesc
    Nov 20 '18 at 21:26










  • I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
    – eyllanesc
    Nov 20 '18 at 21:28










  • This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
    – Heliomaster
    Nov 20 '18 at 21:34
















0














I am trying to create a small program which should display a tableview based on sqlite table where dates are stored. When a validity is passed the cell shows red to indicate the validity has expired. I have a method "get_date_diff" which retrieves the emails and dates expired and stores them in lists to later use those as variable for mails to be sent in batch i.e: Email(var) has the certificate (var) expired on date (var). My if statement gets me the expired dates and the emails in the listes_pilotes and mail_pilotes i need the third list to be filled with the culprit certificate : was it in column certificate1, certificate2 or possibly both:



def get_date_diff(self):
'''method to retrieve from DB expired certificates '''
query = QSqlQuery("SELECT pilot_1,certificate1,certificate2,pilot_mail FROM Pilots")
liste_pilotes =
mail_pilotes =
#certificate_expired = needs to be filled
append_new = liste_pilotes.append
append_new_mail = mail_pilotes.append
while query_time.next():
pilot_1 = query.value(0)
date1 = query.value(1)
date2 = query.value(2)
pilot_mail = query.value(3)
alter_certif1 = datetime.strptime(date1,"%Y-%m-%d")
alter_certif2 = datetime.strptime(date2,"%Y-%m-%d")
if alter_date1 < datetime.now() or alter_date2 < datetime.now():
append_new(pilot_1)
append_new_mail(pilot_mail)
return liste_pilotes,mail_pilotes


SAMPLE OF THE TABLE



the DB on which the tableview is based:



from PyQt5.QtSql import *

class LmtDataBase():
def __init__(self):
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("LmtPilots.db")

self.db.open()

query = QSqlQuery()
query.exec_('''CREATE TABLE Pilots(id INTEGER PRIMARY KEY,pilot_1 TEXT, datetime1 TEXT, datetime2 TEXT,pilot_mail TEXT)''')

self.db.commit()
self.db.close()

# ...









share|improve this question
























  • Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
    – eyllanesc
    Nov 20 '18 at 20:57










  • Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
    – Heliomaster
    Nov 20 '18 at 21:23












  • In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
    – eyllanesc
    Nov 20 '18 at 21:26










  • I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
    – eyllanesc
    Nov 20 '18 at 21:28










  • This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
    – Heliomaster
    Nov 20 '18 at 21:34














0












0








0







I am trying to create a small program which should display a tableview based on sqlite table where dates are stored. When a validity is passed the cell shows red to indicate the validity has expired. I have a method "get_date_diff" which retrieves the emails and dates expired and stores them in lists to later use those as variable for mails to be sent in batch i.e: Email(var) has the certificate (var) expired on date (var). My if statement gets me the expired dates and the emails in the listes_pilotes and mail_pilotes i need the third list to be filled with the culprit certificate : was it in column certificate1, certificate2 or possibly both:



def get_date_diff(self):
'''method to retrieve from DB expired certificates '''
query = QSqlQuery("SELECT pilot_1,certificate1,certificate2,pilot_mail FROM Pilots")
liste_pilotes =
mail_pilotes =
#certificate_expired = needs to be filled
append_new = liste_pilotes.append
append_new_mail = mail_pilotes.append
while query_time.next():
pilot_1 = query.value(0)
date1 = query.value(1)
date2 = query.value(2)
pilot_mail = query.value(3)
alter_certif1 = datetime.strptime(date1,"%Y-%m-%d")
alter_certif2 = datetime.strptime(date2,"%Y-%m-%d")
if alter_date1 < datetime.now() or alter_date2 < datetime.now():
append_new(pilot_1)
append_new_mail(pilot_mail)
return liste_pilotes,mail_pilotes


SAMPLE OF THE TABLE



the DB on which the tableview is based:



from PyQt5.QtSql import *

class LmtDataBase():
def __init__(self):
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("LmtPilots.db")

self.db.open()

query = QSqlQuery()
query.exec_('''CREATE TABLE Pilots(id INTEGER PRIMARY KEY,pilot_1 TEXT, datetime1 TEXT, datetime2 TEXT,pilot_mail TEXT)''')

self.db.commit()
self.db.close()

# ...









share|improve this question















I am trying to create a small program which should display a tableview based on sqlite table where dates are stored. When a validity is passed the cell shows red to indicate the validity has expired. I have a method "get_date_diff" which retrieves the emails and dates expired and stores them in lists to later use those as variable for mails to be sent in batch i.e: Email(var) has the certificate (var) expired on date (var). My if statement gets me the expired dates and the emails in the listes_pilotes and mail_pilotes i need the third list to be filled with the culprit certificate : was it in column certificate1, certificate2 or possibly both:



def get_date_diff(self):
'''method to retrieve from DB expired certificates '''
query = QSqlQuery("SELECT pilot_1,certificate1,certificate2,pilot_mail FROM Pilots")
liste_pilotes =
mail_pilotes =
#certificate_expired = needs to be filled
append_new = liste_pilotes.append
append_new_mail = mail_pilotes.append
while query_time.next():
pilot_1 = query.value(0)
date1 = query.value(1)
date2 = query.value(2)
pilot_mail = query.value(3)
alter_certif1 = datetime.strptime(date1,"%Y-%m-%d")
alter_certif2 = datetime.strptime(date2,"%Y-%m-%d")
if alter_date1 < datetime.now() or alter_date2 < datetime.now():
append_new(pilot_1)
append_new_mail(pilot_mail)
return liste_pilotes,mail_pilotes


SAMPLE OF THE TABLE



the DB on which the tableview is based:



from PyQt5.QtSql import *

class LmtDataBase():
def __init__(self):
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("LmtPilots.db")

self.db.open()

query = QSqlQuery()
query.exec_('''CREATE TABLE Pilots(id INTEGER PRIMARY KEY,pilot_1 TEXT, datetime1 TEXT, datetime2 TEXT,pilot_mail TEXT)''')

self.db.commit()
self.db.close()

# ...






python pyqt pyqt5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 21:45









eyllanesc

73.8k103056




73.8k103056










asked Nov 20 '18 at 20:39









Heliomaster

1247




1247












  • Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
    – eyllanesc
    Nov 20 '18 at 20:57










  • Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
    – Heliomaster
    Nov 20 '18 at 21:23












  • In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
    – eyllanesc
    Nov 20 '18 at 21:26










  • I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
    – eyllanesc
    Nov 20 '18 at 21:28










  • This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
    – Heliomaster
    Nov 20 '18 at 21:34


















  • Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
    – eyllanesc
    Nov 20 '18 at 20:57










  • Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
    – Heliomaster
    Nov 20 '18 at 21:23












  • In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
    – eyllanesc
    Nov 20 '18 at 21:26










  • I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
    – eyllanesc
    Nov 20 '18 at 21:28










  • This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
    – Heliomaster
    Nov 20 '18 at 21:34
















Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
– eyllanesc
Nov 20 '18 at 20:57




Could you explain me better, what does the title of your question have to do with the content of it? Also, you do not explain it clearly, maybe with some sample data, if you are using sqlite it would be advisable that you share the .db, if you are using Another database may share a .sql that can generate a test data.
– eyllanesc
Nov 20 '18 at 20:57












Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
– Heliomaster
Nov 20 '18 at 21:23






Hi @eyllanesc, I have added a picture of the intended program.As you can see in this example smith has certifi1 and 2 expired, williams only certif2 and klein certif1. The function( method really) returns the name and and the email off that table in the list to later use it. The problem: I do i get to know if red came from column 1 i.e certif1 or column2 i.e certif2?
– Heliomaster
Nov 20 '18 at 21:23














In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
– eyllanesc
Nov 20 '18 at 21:26




In the visual example that shows, what should the output of get_date_diff be? Could you share the .db?
– eyllanesc
Nov 20 '18 at 21:26












I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
– eyllanesc
Nov 20 '18 at 21:28




I point it out to you because what output if both certificates are expired, or if only one or only the second ?, I understand that for the last cases it is enough to indicate 2 or 3, but in the case of both?
– eyllanesc
Nov 20 '18 at 21:28












This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
– Heliomaster
Nov 20 '18 at 21:34




This is only a draft code eventually I'll have probably 12 columns with 12 certificates to check. So it will be for example certif 6,9 and 10 for one guy, the other will have maybe only 1 or maybe all ....
– Heliomaster
Nov 20 '18 at 21:34












1 Answer
1






active

oldest

votes


















1














The idea is to get the dates and compare by storing them in a list, and if that list has at least one item save the other data:



from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
return False

query = QtSql.QSqlQuery()
query.exec_('''CREATE TABLE Pilots(
id INTEGER PRIMARY KEY,
pilot_1 TEXT,
certificate1 TEXT,
certificate2 TEXT,
certificate3 TEXT,
pilot_mail TEXT
)''')

for i in range(100):
query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
query.addBindValue(i)
query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
for j in range(3):
days = random.randint(-10*365, 10*365)
query.addBindValue(QtCore.QDate.currentDate().addDays(days))
query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
if not query.exec_():
print("error: ", query.lastError().text())
return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateDelegate, self).initStyleOption(option, index)
t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
if t < QtCore.QDate.currentDate():
option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableview = QtWidgets.QTableView()
self.setCentralWidget(tableview)
query = QtSql.QSqlQuery()
query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
model = QtSql.QSqlQueryModel(self)
model.setQuery(query)
tableview.setModel(model)
for name in ('certificate1', 'certificate2'):
ix = query.record().indexOf(name)
delegate = DateDelegate(tableview)
tableview.setItemDelegateForColumn(ix, delegate)
print(self.get_date_diff())

def get_date_diff(self):
query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
rec = query.record()
cols = [rec.indexOf(name) for name in ("certificate1", "certificate2")]
results =
while query.next():
pilot_1 = query.value(rec.indexOf("pilot_1"))
pilot_mail = query.value(rec.indexOf("pilot_mail"))
dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
if filter_columns:
v = [pilot_1, pilot_mail, filter_columns]
results.append(v)
return results

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())





share|improve this answer





















  • Exactly what I needed, brilliant code. Thanks @eyllanesc!
    – Heliomaster
    Nov 21 '18 at 7:38











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401151%2freturn-column-name-from-qsqlquery%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














The idea is to get the dates and compare by storing them in a list, and if that list has at least one item save the other data:



from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
return False

query = QtSql.QSqlQuery()
query.exec_('''CREATE TABLE Pilots(
id INTEGER PRIMARY KEY,
pilot_1 TEXT,
certificate1 TEXT,
certificate2 TEXT,
certificate3 TEXT,
pilot_mail TEXT
)''')

for i in range(100):
query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
query.addBindValue(i)
query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
for j in range(3):
days = random.randint(-10*365, 10*365)
query.addBindValue(QtCore.QDate.currentDate().addDays(days))
query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
if not query.exec_():
print("error: ", query.lastError().text())
return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateDelegate, self).initStyleOption(option, index)
t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
if t < QtCore.QDate.currentDate():
option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableview = QtWidgets.QTableView()
self.setCentralWidget(tableview)
query = QtSql.QSqlQuery()
query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
model = QtSql.QSqlQueryModel(self)
model.setQuery(query)
tableview.setModel(model)
for name in ('certificate1', 'certificate2'):
ix = query.record().indexOf(name)
delegate = DateDelegate(tableview)
tableview.setItemDelegateForColumn(ix, delegate)
print(self.get_date_diff())

def get_date_diff(self):
query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
rec = query.record()
cols = [rec.indexOf(name) for name in ("certificate1", "certificate2")]
results =
while query.next():
pilot_1 = query.value(rec.indexOf("pilot_1"))
pilot_mail = query.value(rec.indexOf("pilot_mail"))
dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
if filter_columns:
v = [pilot_1, pilot_mail, filter_columns]
results.append(v)
return results

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())





share|improve this answer





















  • Exactly what I needed, brilliant code. Thanks @eyllanesc!
    – Heliomaster
    Nov 21 '18 at 7:38
















1














The idea is to get the dates and compare by storing them in a list, and if that list has at least one item save the other data:



from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
return False

query = QtSql.QSqlQuery()
query.exec_('''CREATE TABLE Pilots(
id INTEGER PRIMARY KEY,
pilot_1 TEXT,
certificate1 TEXT,
certificate2 TEXT,
certificate3 TEXT,
pilot_mail TEXT
)''')

for i in range(100):
query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
query.addBindValue(i)
query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
for j in range(3):
days = random.randint(-10*365, 10*365)
query.addBindValue(QtCore.QDate.currentDate().addDays(days))
query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
if not query.exec_():
print("error: ", query.lastError().text())
return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateDelegate, self).initStyleOption(option, index)
t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
if t < QtCore.QDate.currentDate():
option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableview = QtWidgets.QTableView()
self.setCentralWidget(tableview)
query = QtSql.QSqlQuery()
query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
model = QtSql.QSqlQueryModel(self)
model.setQuery(query)
tableview.setModel(model)
for name in ('certificate1', 'certificate2'):
ix = query.record().indexOf(name)
delegate = DateDelegate(tableview)
tableview.setItemDelegateForColumn(ix, delegate)
print(self.get_date_diff())

def get_date_diff(self):
query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
rec = query.record()
cols = [rec.indexOf(name) for name in ("certificate1", "certificate2")]
results =
while query.next():
pilot_1 = query.value(rec.indexOf("pilot_1"))
pilot_mail = query.value(rec.indexOf("pilot_mail"))
dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
if filter_columns:
v = [pilot_1, pilot_mail, filter_columns]
results.append(v)
return results

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())





share|improve this answer





















  • Exactly what I needed, brilliant code. Thanks @eyllanesc!
    – Heliomaster
    Nov 21 '18 at 7:38














1












1








1






The idea is to get the dates and compare by storing them in a list, and if that list has at least one item save the other data:



from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
return False

query = QtSql.QSqlQuery()
query.exec_('''CREATE TABLE Pilots(
id INTEGER PRIMARY KEY,
pilot_1 TEXT,
certificate1 TEXT,
certificate2 TEXT,
certificate3 TEXT,
pilot_mail TEXT
)''')

for i in range(100):
query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
query.addBindValue(i)
query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
for j in range(3):
days = random.randint(-10*365, 10*365)
query.addBindValue(QtCore.QDate.currentDate().addDays(days))
query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
if not query.exec_():
print("error: ", query.lastError().text())
return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateDelegate, self).initStyleOption(option, index)
t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
if t < QtCore.QDate.currentDate():
option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableview = QtWidgets.QTableView()
self.setCentralWidget(tableview)
query = QtSql.QSqlQuery()
query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
model = QtSql.QSqlQueryModel(self)
model.setQuery(query)
tableview.setModel(model)
for name in ('certificate1', 'certificate2'):
ix = query.record().indexOf(name)
delegate = DateDelegate(tableview)
tableview.setItemDelegateForColumn(ix, delegate)
print(self.get_date_diff())

def get_date_diff(self):
query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
rec = query.record()
cols = [rec.indexOf(name) for name in ("certificate1", "certificate2")]
results =
while query.next():
pilot_1 = query.value(rec.indexOf("pilot_1"))
pilot_mail = query.value(rec.indexOf("pilot_mail"))
dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
if filter_columns:
v = [pilot_1, pilot_mail, filter_columns]
results.append(v)
return results

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())





share|improve this answer












The idea is to get the dates and compare by storing them in a list, and if that list has at least one item save the other data:



from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import random
import string

def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
return False

query = QtSql.QSqlQuery()
query.exec_('''CREATE TABLE Pilots(
id INTEGER PRIMARY KEY,
pilot_1 TEXT,
certificate1 TEXT,
certificate2 TEXT,
certificate3 TEXT,
pilot_mail TEXT
)''')

for i in range(100):
query.prepare("insert into Pilots values (?, ?, ?, ?, ?, ?)")
query.addBindValue(i)
query.addBindValue("".join(random.sample(string.ascii_letters, 15)))
for j in range(3):
days = random.randint(-10*365, 10*365)
query.addBindValue(QtCore.QDate.currentDate().addDays(days))
query.addBindValue("".join(random.sample(string.ascii_letters, 4) + ["@mail.com"]))
if not query.exec_():
print("error: ", query.lastError().text())
return True

class DateDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(DateDelegate, self).initStyleOption(option, index)
t = QtCore.QDate.fromString(index.data(), "yyyy-MM-dd")
if t < QtCore.QDate.currentDate():
option.backgroundBrush = QtGui.QBrush(QtGui.QColor("red"))



class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableview = QtWidgets.QTableView()
self.setCentralWidget(tableview)
query = QtSql.QSqlQuery()
query.exec_('''SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots''')
model = QtSql.QSqlQueryModel(self)
model.setQuery(query)
tableview.setModel(model)
for name in ('certificate1', 'certificate2'):
ix = query.record().indexOf(name)
delegate = DateDelegate(tableview)
tableview.setItemDelegateForColumn(ix, delegate)
print(self.get_date_diff())

def get_date_diff(self):
query = QtSql.QSqlQuery("SELECT pilot_1, certificate1, certificate2, pilot_mail FROM Pilots")
rec = query.record()
cols = [rec.indexOf(name) for name in ("certificate1", "certificate2")]
results =
while query.next():
pilot_1 = query.value(rec.indexOf("pilot_1"))
pilot_mail = query.value(rec.indexOf("pilot_mail"))
dates = [QtCore.QDate.fromString(query.value(col), "yyyy-MM-dd") for col in cols]
filter_columns = [col for col, date in zip(cols, dates) if date < QtCore.QDate.currentDate()]
if filter_columns:
v = [pilot_1, pilot_mail, filter_columns]
results.append(v)
return results

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 22:37









eyllanesc

73.8k103056




73.8k103056












  • Exactly what I needed, brilliant code. Thanks @eyllanesc!
    – Heliomaster
    Nov 21 '18 at 7:38


















  • Exactly what I needed, brilliant code. Thanks @eyllanesc!
    – Heliomaster
    Nov 21 '18 at 7:38
















Exactly what I needed, brilliant code. Thanks @eyllanesc!
– Heliomaster
Nov 21 '18 at 7:38




Exactly what I needed, brilliant code. Thanks @eyllanesc!
– Heliomaster
Nov 21 '18 at 7:38


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401151%2freturn-column-name-from-qsqlquery%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin