I've created a small sqlite3 database using peewee to try to understand foreign keys and get them working in a simple database.
from peewee import *
db = SqliteDatabase('database.db')
class Category(Model):
category = CharField()
class Meta:
database = db
class Subcat(Model):
description = BlobField()
sub_cat = CharField()
top_category = ForeignKeyField(Category, related_name='group')
class Meta:
database = db
db.connect()
db.create_tables([Category, Subcat], safe=True)
I have then created a controller.py file to handle all the database transactions.
(Updated)
from peewee import *
from database import *
class ModCat(Category):
def add_cat(self,category):
update = Category.create(category=category)
def get_cat(self):
categories = Category.select(Category.category).order_by(Category.category)
return categories
class ModSubCat(Subcat):
def save_sub_cat(self, sub, master, desc):
name = Category().select().where(Category.name==master)
update = Subcat.create(sub_cat=sub, top_category=name, description=desc)
Finally, a main.py that allows me to enter data into the database with a simple form created in wxFormBuilder.
from gui import *
from controller import *
class Menu(InDb):
def __init__(self, parent):
InDb.__init__(self, parent)
get_categories = ModCat()
list = get_categories.get_cat()
new_list = []
for thing in list:
new_list.append(thing.category)
print new_list
for f in new_list:
self.m_comboBox1.Append(f)
def click_save( self, event ):
new_cat = ModCat()
new_cat.add_cat(self.m_textCtrl3.GetValue())
self.GetParent() # This assigns parent frame to frame.
self.Close() # This then closes frame removing the main menu.
frame = Menu(None)
frame.Centre()
frame.Show()
def sub_save( self, event ):
sub = self.m_textCtrl5.GetValue()
master = self.m_comboBox1.GetValue()
desc = "Hi"
update = ModSubCat()
update.save_sub_cat(sub, master, desc)
#Start App by calling sub class of MainMenu
if __name__ == '__main__':
app = wx.App(0)
frame = Menu(None)
frame.Centre()
frame.Show()
app.MainLoop()
The database creates with no errors but when I run main.py it always returns this error.
Traceback (most recent call last):
File "C:/Users/********/PycharmProjects/RAMS/main.py", line 2, in <module>
from controller import *
File "C:\Users\********\PycharmProjects\RAMS\controller.py", line 13, in <module>
class ModSubCat(Subcat):
File "C:\Python27\lib\site-packages\peewee.py", line 4710, in __new__
field.add_to_class(cls, name)
File "C:\Python27\lib\site-packages\peewee.py", line 1437, in add_to_class
invalid('The related_name of %(field)s ("%(backref)s") '
File "C:\Python27\lib\site-packages\peewee.py", line 1431, in invalid
raise AttributeError(msg % context)
AttributeError: The related_name of modsubcat.top_category ("group") is already in use by another foreign key.
I've changed related_by value with no luck.
Is the fact that I have a Sub Class ModSubCat in controller.py causing a problem?
Ive removed the related_name='group'
from
top_category = ForeignKeyField(Category, related_name='group') and now all works.
What is the related_name for?
Related
I have an app contains these models
class Transaction(models.Model):
chp_reference = models.CharField(max_length=50, unique=True)
rent_effective_date = ..
income_period = ..
property_market_rent =..
number_of_family_group = ..
cruser = ..
prop_id = ..
state = ..
group =..
class FamilyGroup(models.Model):
name = models.CharField(..
transaction =models.ForeignKey(Transaction,..
...
class FamilyMember(models.Model):
transaction = models.ForeignKey(Transaction, ..
family_group = models.ForeignKey(FamilyGroup..
name = models.CharField..
date_of_birth = models.DateField..
....
Im trying to make Imports app that will accept xlsx files with some certain format.
after i imported the models from the other apps, therefore i've created a model that have a field for each field i n the above models , i removed a lot so it look readable.
im trying to make it update_or_create since i think its the best approach to do, since maybe in future maybe i want to update some fields. I have created the first update_or_create for Transaction but since family_group and family_member are childs of Transaction and Inlines i cant figure out how to apply this. the main idea is i have a transaction contains family_groups and family_members inside it .
class Batch(models.Model):
batch = models.CharField(max_length=50)
transaction_chp_reference = models.CharField(unique=True)
transaction_rent_effective_date = models.DateField(..
transaction_property_market_rent = models.DecimalField(..
transaction_number_of_family_group = models.PositiveSmallIntegerField(..
family_group_name = models.CharField(..
family_group_family_type = models.CharField(..
family_group_alloc_id = models.PositiveIntegerField(..
family_group_last_rent = models.DecimalField(..
family_member_name = models.CharField(..
family_member_contact_id = models.PositiveIntegerField(..
family_member_surname = models.CharField(..
family_member_partnered = models.BooleanField(..
def __str__(self):
return str(self.batch)
def save(self, *args, **kwargs):
self.message = ''
if self.transaction_chp_reference:
trans, t = Transaction.objects.update_or_create(
# filter on the unique value of `chp_reference`
chp_reference=self.transaction_chp_reference,
# update these fields, or create a new object with these values
defaults={
'income_period':self.transaction_income_period,
'property_market_rent':self.transaction_property_market_rent,
'number_of_family_group':self.transaction_number_of_family_group,
'rent_effective_date':self.transaction_rent_effective_date,
'cruser':self.transaction_cruser,
'prop_id':self.transaction_prop_id,
'state':self.transaction_state,
}
)
self.message += 'Transaction "' + str(trans.chp_reference) + '" Created\n'
obj, mt = MaintenanceType.objects.update_or_create(
name=self.family_group_maintenance_type,
)
obj, ft = FamilySituation.objects.update_or_create(
name= self.family_group_family_type,
)
obj, fg = FamilyGroup.objects.update_or_create(
transaction=t,
name=self.family_group_name,
defaults={
'alloc_id':self.family_group_alloc_id,
'any_income_support_payment':self.family_group_any_income_support_payment,
'cra_amount':self.family_group_cra_amount,
'cra_eligibilty':self.family_group_cra_eligibilty,
'family_type':ft,
'ftb_a':self.family_group_ftb_a,
'ftb_b':self.family_group_ftb_b,
'last_rent':self.family_group_last_rent,
'maintenance_amount':self.family_group_maintenance_amount,
'maintenance_type':mt,
'name':self.family_group_name,
'number_of_additional_children':self.family_group_number_of_additional_children,
}
)
self.message += 'Family Group "' + str(obj.name) + '" Created\n'
now im getting an error when try to import xlsx file:
Cannot assign "False": "FamilyGroup.transaction" must be a "Transaction" instance.
Traceback:
Traceback (most recent call last):
File "E:\15-12\venv\lib\site-packages\django\db\models\query.py", line 575, in update_or_create
obj = self.select_for_update().get(**kwargs)
File "E:\15-12\venv\lib\site-packages\django\db\models\query.py", line 417, in get
self.model._meta.object_name
calculator.models.FamilyGroup.DoesNotExist: FamilyGroup matching query does not exist.
UPDATE
I have replaced the save() method with this code.
#receiver(post_save, sender=Batch)
def post_save_tranaction(sender, instance, created, **kwargs):
message = ''
if created:
Transaction.objects.update_or_create(
chp_reference=instance.transaction_chp_reference, defaults=
{rent_effective_date':instance.rent_effective_date,... , ... })
## now since FamilyGroup is a child (Foreignkey) to Transaction
## im not sure how to make it instance of Transaction
## FamilyMember is also a child of FamilyGroup and Transaction - same issue
## i tried this --->
transactions = []
transaction = Transaction.objects.all()
for i in transaction:
transactions.append(i.pk)
FamilyGroup.objects.update_or_create(name=instance.family_group_name,
transaction__in=transactions
)
I just start a simple project called flask_wiki this days and I'm using some flask extensions as the follows:
Flask-SQLAlchemy
Flask-Restful
MarshMallow
Well, I just discovered that the MarshMallow project provides a class called 'ModelSchema', which reads all fields from my SQLAlchemy Model and provide a fully automated (de)serialializer.
In my case, I created a 'GUID' Field which is RDBM agnostic and inserted it on my Sqlalchemy model as follows:
from flask.ext.sqlalchemy import SQLAlchemy
from flask_wiki.backend.custom_fields import GUIDField
class Page(db.Model):
"""
Implements the Page Model.
"""
guid = db.Column(GUIDField, primary_key=True, default=uuid.uuid4)
name = db.Column(db.String, nullable=False)
raw_content = db.Column(db.Text)
rendered_content = db.Column(db.Text)
def __repr__(self):
return self.__str__()
def __str__(self):
return self.name
The GUIDField is implemented is this way:
from sqlalchemy.types import TypeDecorator, CHAR
import uuid
class GUIDField(TypeDecorator):
# Platform independent GUID Implementation that uses little endianess.
impl = CHAR
def load_dialect_impl(self, dialect):
return dialect.type_descriptor(CHAR(32))
def process_bind_param(self, value, dialect):
if value is None:
return value
else:
if isinstance(value, uuid.UUID):
return value.bytes_le
def process_result_value(self, value, dialect):
if value is None:
return value
else:
return uuid.UUID(bytes_le=value)
The code for create test objects (through mixer) is working; all the guids are generated and verified correctly.
With this in mind, a just created the following MarshMallow Serializer Field:
from marshmallow import fields
import uuid
class GUIDSerializationField(fields.Field):
def _serialize(self, value, attr, obj):
if value is None:
return value
else:
if isinstance(value, uuid.UUID):
return str(value)
else:
return None
Finally, I created the SerializerClass:
from flask_wiki.backend.backend import marsh
from flask_wiki.backend.custom_serialization_fields import GUIDSerializationField
from flask_wiki.backend.models import Page
from marshmallow import fields
class PageSchema(marsh.ModelSchema):
class Meta:
model = Page
guid = GUIDSerializationField()
page_schema = PageSchema()
pages_schema = PageSchema(many=True)
I tried to use this last code with and without inserting the guid field, but in all cases the following error occurs:
Traceback (most recent call last):
File "/home/arthas/dev/flask-wiki/flask_wiki/wiki.py", line 3, in <module>
from flask_wiki.backend import backend
File "/home/arthas/dev/flask-wiki/flask_wiki/backend/__init__.py", line 1, in <module>
import flask_wiki.backend.routes
File "/home/arthas/dev/flask-wiki/flask_wiki/backend/routes.py", line 2, in <module>
from flask_wiki.backend.views import PageView
File "/home/arthas/dev/flask-wiki/flask_wiki/backend/views.py", line 3, in <module>
from flask_wiki.backend.serializers import pages_schema, page_schema
File "/home/arthas/dev/flask-wiki/flask_wiki/backend/serializers.py", line 7, in <module>
class PageSchema(marsh.ModelSchema):
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow/schema.py", line 116, in __new__
dict_cls=dict_cls
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/schema.py", line 53, in get_declared_fields
declared_fields = mcs.get_fields(converter, opts)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/schema.py", line 77, in get_fields
return converter.fields_for_model(opts.model, fields=opts.fields, exclude=opts.exclude)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/convert.py", line 75, in fields_for_model
field = self.property2field(prop)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/convert.py", line 93, in property2field
field_class = self._get_field_class_for_property(prop)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/convert.py", line 151, in _get_field_class_for_property
field_cls = self._get_field_class_for_column(column)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/convert.py", line 121, in _get_field_class_for_column
return self._get_field_class_for_data_type(column.type)
File "/home/arthas/env/wiki/lib/python3.5/site-packages/marshmallow_sqlalchemy/convert.py", line 143, in _get_field_class_for_data_type
'Could not find field column of type {0}.'.format(types[0]))
marshmallow_sqlalchemy.exceptions.ModelConversionError: Could not find field column of type <class 'flask_wiki.backend.custom_fields.GUIDField'>.
So, I finally ask: how to use marshmallow to serialize a custom sqlalchemy field?
You need to create your own Converter.
Try something like this:
import uuid
from flask_wiki.backend.models import Page
from flask_wiki.backend.backend import marsh
from marshmallow_sqlalchemy.convert import ModelConverter
from flask_wiki.backend.custom_fields import GUIDField
from marshmallow import fields
#Here you are overwriting the list of types of the SQLAlchemy, adding your custom type
class GUIDConverter(ModelConverter):
SQLA_TYPE_MAPPING = dict(
list(ModelConverter.SQLA_TYPE_MAPPING.items()) +
[(GUIDField, fields.Str)]
)
class GUIDSerializationField(fields.Field):
def _serialize(self, value, attr, obj):
if value is None:
return value
else:
if isinstance(value, uuid.UUID):
return str(value)
else:
return None
class PageSchema(marsh.ModelSchema):
class Meta:
model = Page
model_converter = GUIDConverter #Tell to Marshmallow to use your custom converter for this model
guid = GUIDSerializationField(attribute="guid")
You can also see this link for help.
I hope it helped and sorry for my bad english
According to what I've read in the docs, you can specify a model_converter attribute in your ModelSchema Meta class. The ModelConverter class has a SQLA_TYPE_MAPPING attribute you can override in a subclass to add your custom GUID field to the types detected by the automatic schema generator.
That said, I've never used it so I don't know if this will work or not.
The following set-up illustrates my problem:
from peewee import (Model,
SqliteDatabase)
from peewee import (CharField,
ForeignKeyField,
IntegerField)
from playhouse.shortcuts import model_to_dict
database = SqliteDatabase(':memory:')
class BaseModel(Model):
class Meta:
database = database
class Description(BaseModel):
i_am = CharField(
db_column='I_AM'
)
class Meta:
db_table = 'DESCRIPTION'
# This is not a table, just a convenient class to inherit from.
class ValueBase(BaseModel):
value = IntegerField(
db_column='VALUE'
)
description = ForeignKeyField(
db_column='I_AM_ID',
rel_model=Description,
to_field='id'
)
class SpecificValue(ValueBase):
class Meta:
db_table = 'SPECIFIC_VALUE'
if __name__ == '__main__':
models = [Description, SpecificValue]
database.create_tables(models)
description = Description(
i_am = 'prime'
)
description.save()
specific = SpecificValue(
value=7,
description=description
)
specific.save()
### This works
print model_to_dict(
specific
)
### This does NOT work
print model_to_dict(
specific,
backrefs=True
)
The problem is that when I use model_to_dict and ask for back references, then the function thinks specific is in a table valuebase and not in a table called SPECIFIC_VALUE. Does anyone know how to do this sort of inheritance and correctly set table names?
EDIT
The traceback is as follows:
Traceback (most recent call last):
File "/home/lafras/Projects/Cloud/eg.py", line 61, in <module>
backrefs=True
File "build/bdist.linux-x86_64/egg/playhouse/shortcuts.py", line 96, in model_to_dict
File "build/bdist.linux-x86_64/egg/playhouse/shortcuts.py", line 117, in model_to_dict
File "build/bdist.linux-x86_64/egg/peewee.py", line 2794, in __iter__
File "build/bdist.linux-x86_64/egg/peewee.py", line 2787, in execute
File "build/bdist.linux-x86_64/egg/peewee.py", line 2470, in _execute
File "build/bdist.linux-x86_64/egg/peewee.py", line 3199, in execute_sql
File "build/bdist.linux-x86_64/egg/peewee.py", line 3048, in __exit__
File "build/bdist.linux-x86_64/egg/peewee.py", line 3191, in execute_sql
peewee.OperationalError: no such table: valuebase
If SpecificValue inherits directly from BaseModel:
class SpecificValue(BaseModel):
value = IntegerField(
db_column='VALUE'
)
description = ForeignKeyField(
db_column='I_AM_ID',
rel_model=Description,
to_field='id'
)
class Meta:
db_table = 'SPECIFIC_VALUE'
then the output is as expected:
{'id': 1, 'value': 7, 'description': {'id': 1, 'i_am': 'prime'}}
Can you explain a bit more thoroughly what's not working correctly? I don't see any back-references that would be associated with the SpecificValue table, since there are not other models that have a foreign key to it.
EDIT:
OK, so what's happening here is that when you specify backrefs, peewee is trying to go from:
SpecificValue -> Description -> ValueBase (which has a foreign key to description).
The fix is to explicitly exclude the backref:
model_to_dict(specific, backrefs=True, exclude=[Description.valuebase_set])
I am creating a program with python 2.7, using Tkinter as the GUI, and elementtree, where the data entered by the user is stored in an XML file. I have managed to create the XML file using python and this saves to the file 'crimeFile.xml', with all empty tags. The GUI also displays the fields and text boxes that allow the user to enter in text. The problem is that when I try and save an entry, I get an error, and the data is not saved to the XML file.
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
import xml.etree.ElementTree as ET
from Tkinter import *
class Application(Frame):
def create_XML(self):
crimeReport = Element('crime report')
caseNo = SubElement(crimeReport, 'case number')
victimDetails = SubElement(caseNo, 'victim details')
victimFirstName = SubElement(victimDetails, 'victims first name')
victimSecondName = SubElement(victimDetails, 'victim surname')
victimAddress = SubElement(victimDetails, 'victim address')
output_file = open('crimeFile.xml', 'w')
output_file.write('<?xml version="1.0"?>')
output_file.write(ElementTree.tostring(crimeReport))
output_file.close()
def save_XML(self):
record = ET.SubElement(self.crimeReport, 'crime report')
caseNoNode = ET.SubElement(record, 'case number')
caseNoNode.text = self.caseNo.get()
victimFirstNameNode = ET.SubElement(record, 'first name')
victimFirstNameNode.text = self.victimFirstName.get()
victimSecondNameNode = ET.SubElement(record, 'surname')
victimSecondNameNode.text = self.victimSecondName.get()
victimAddressNode = ET.SubElement(record, 'address')
victimAddressNode.text = self.victimAddress.get()
self.tree.write('crimeReport.xml')
self.clear_field()
def create_Widgets(self):
self.save = Button(self)
self.save["text"] = "Save",
self.save["command"] = self.save_XML
self.save["bg"] = "cyan"
self.save.grid(row=0,column =2,sticky=W+E+N+S)
self.crimeReportLabel = Label(self, text = 'Crime Report')
self.crimeReportLabel.grid(row=1,column =1,sticky=W)
self.caseNoLabel = Label(self,text="Case Number")
self.caseNoLabel.grid(row=2,column =1,sticky=W)
self.caseNo = Entry(self)
self.caseNo.grid(row=2,column =2,sticky=W)
self.victimDetailsLabel = Label(self,text="Victim Details")
self.victimDetailsLabel.grid(row=3,column =1,sticky=W)
self.victimFirstNameLabel = Label(self,text="First Name")
self.victimFirstNameLabel.grid(row=4,column =1,sticky=W)
self.victimFirstName = Entry(self)
self.victimFirstName.grid(row=4,column =2,sticky=W)
self.victimSecondNameLabel = Label(self,text="Surname")
self.victimSecondNameLabel.grid(row=4,column =3,sticky=W)
self.victimSecondName = Entry(self)
self.victimSecondName.grid(row=4,column =4,sticky=W)
self.victimAddressLabel = Label(self,text="Address")
self.victimAddressLabel.grid(row=6,column =1,sticky=W)
self.victimAddress = Entry(self)
self.victimAddress.grid(row=6,column =2,sticky=W)
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid(column=5,row=25)
self.create_Widgets()
self.create_XML()
crimeReport = Tk()
app = Application(master = crimeReport)
app.mainloop()
crimeReport.destroy()
The error that I get is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Users\Laleh\workspace\AdvDB20-02\program1\program1.py", line 60, in save_XML
record = ET.SubElement(self.crimeReport, 'crime report')
AttributeError: Application instance has no attribute 'crimeReport'
What the program is meant to do is create an XML file to use, for multiple entries by the user. Update and store the new entries in this XML file (not overriding the previous ones), so that later it can be searched and a report produced.
I'm a newbie to python and am not sure where I am going wrong?
Your application instance doesn't have any attribute named crimeReport
def save_XML(self):
record = ET.SubElement(self.crimeReport, 'crime report')
^
crimeReport is only defined in your create_XML method. You can define crimeReport as class attribute instead.
class Application(Frame):
crimeReport = Element('crime report')
and use self.crimeReport in your methods
I am running python version 2.7.8. I am storing project titles in a sqlite database that I am trying to import into a combobox. When I try and import the project titles from the sqlite database and import them into the combobox I get this error: TypeError: 'unicode' object is not callable
Here is my code:
main.py
from EvDB import EvDB
import wx
from ProjectsPanel import ProjectsPanel
class MyFrame(wx.Frame):
""" We simply derive a new class of Frame. """
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title=title, size=(650,725))
# Create Database Tables
self.db = EvDB(self)
self.db.createTbls()
main = wx.Panel(self)
self.projectsPg = ProjectsPanel(main, -1)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.mainSizer.Add(self.projectsPg, 1, wx.ALL|wx.EXPAND)
main.SetAutoLayout(True)
main.SetSizer(self.mainSizer)
self.mainSizer.Fit(main)
self.Layout()
self.Show()
self.UserID = 1
rows = self.db.getProjects(self.UserID)
print(rows)
print(str(rows))
self.projectsPg.cb.Value(rows)
app = wx.App(False)
ProjectsPanel.py
import wx
from EvDB import EvDB
import sqlite3 as lite
class ProjectsPanel(wx.Panel):
def __init__(self, parent, ID):
wx.Panel.__init__(self, parent, ID)
self.db = lite.connect('evDB.db')
self.cur = self.db.cursor()
self.db2 = EvDB(self)
sizer = wx.BoxSizer(wx.VERTICAL)
# the combobox Control
self.userProjects = ['Before1','Before2', 'Before3', 'Before4']
self.cb = wx.ComboBox(self, value='New', choices=self.userProjects, style=wx.CB_DROPDOWN)
sizer.Add(self.cb, 0, wx.EXPAND)
# Setting Layouts
self.SetAutoLayout(True)
self.SetSizer(sizer)
sizer.Fit(self)
EvDB.py
import sqlite3 as lite
class EvDB():
def __init__(self, parent):
self.db = lite.connect('evDB.db')
self.cur = self.db.cursor()
def createTbls(self):
self.db.execute('''CREATE TABLE IF NOT EXISTS Projects
(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Title varchar(50) DEFAULT NULL,
DateCreated DATE);''')
self.db.execute('''CREATE TABLE IF NOT EXISTS User_x_Project
(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
UserID INT DEFAULT NULL,
ProjectID INT DEFAULT NULL);''')
def getProjects(self,userID):
self.cur.execute("SELECT Title FROM User_x_Project, Projects WHERE User_x_Project.UserID = "+str(userID)+" AND User_x_Project.ProjectID = Projects.ID;")
rows = self.cur.fetchall()
return rows
the print results: [(u'Tests',), (u'Test1',), (u'Test2',), (u'Test3',)]
How do I add the titles stored in my sqlite database to my combobox?
Thank you for any and all help!
EDIT: Here is my entire traceback
C:\Python27\python.exe C:/Users/xxx/xxx/xxx/main.py
[(u'Tests',), (u'Test1',), (u'Test2',), (u'Test3',)]
[(u'Tests',), (u'Test1',), (u'Test2',), (u'Test3',)]
Traceback (most recent call last):
File "C:/Users/xxx/xxx/xxx/main.py", line 43, in <module>
frame = MyFrame(None, -1, 'Small editor')
File "C:/Users/xxx/xxx/xxx/main.py", line 37, in __init__
self.projectsPg.cb.Value(rows)
TypeError: 'unicode' object is not callable
Process finished with exit code 1
self.projectsPg.cb is a ComboBox object, and Value is a property. If you access the property without assignment it will return a string (or unicode). You can't call it.
If you want to set a value to the combox, use property assignment (ComboBox.Value =), or ComboxBox.SetValue:
In addition to that, the rows returned by Cursor.fetchall is a list of tuples. You need to fetch the first one. (In the following example, I omitted return row count check for brevity)
self.projectsPg.cb.Value = rows[0][0]
# OR
self.projectsPg.cb.SetValue(rows[0][0])