select on sub query peewee - subquery

I am wondering if I can do select() on sub_query.
I am able to do join sub_query with any peewee.Model. But when I wrote a sub_query and I wanted to just group by with one of the column
e.g. sub_query.select(sub_query.c.column_1, fn.COUNT(sub_query.c.column2)alias('col2_count')).group_by(sub_query.c.column_1)
query was not nested and was giving SQL syntax error.
(Can't reveal the code)
(I have done alias() on sub_query)
Edit
Example:
class Product(Model):
id = PrimaryKeyField()
name = CharField()
created_date = DateField()
class Part(Model):
id = PrimaryKeyField()
product = ForeignKeyField(Product)
name = CharField()
class ProductError(Model):
id = PrimaryKeyField()
product = ForeignKeyField(Product)
note = CharField()
class PartError(Model):
id = PrimaryKeyField()
part = ForeignKeyField(Part)
error = ForeignKeyField(ErrorMaster)
Here Product can have general error and
parts can have specific error which are predefined in ErrorMaster
I just want to know count of product which have errors against total products date wise. (error is product error or error in any part)
So sub_query is something like
sub_q = Product.select(
Product.created_date,
Product.id.alias('product_id'),
fn.IF(# checks if product has error
ProductError.is_null(True), if no product error check part error
fn.IF(fn.COUNT(PartError.id) == 0, 0, 1), # checks if error count > 0 then there is error in part
1
).alias('is_error')
).join(Part, on=Product.id == Part.product)
.join(ProductError, JOIN_LEFT_OUTER, on=Product.id == ProductError.product)
.join(PartError, JOIN_LEFT_OUTER, on=PartError.part == Part.id)
.where(Product.created_date.between(from_date, to_date))
.group_by(Product.id).alias('some_alias')
# below does not work but I can do this in sql
query = sub_q.select(sub_q.c.created_date,
fn.COUNT(sub_q.c.product_id).alias('total_products'),
fn.SUM(sub_q.c.is_error).alias('product_with_errors'))
.group_by(sub_q.c.created_date)

Related

how to insert multiple rows into sqllite3 database

I am trying to select rows and fetch them from the DB table and then insert them into a list so I can insert all of the rows at once into the database, but I got an error.
def paid_or_returned_buyingchecks(self):
date = datetime.now()
now = date.strftime('%Y-%m-%d')
self.tenlistchecks=[]
self.con = sqlite3.connect('car dealership.db')
self.cursorObj = self.con.cursor()
self.dashboard_buying_checks_dates = self.cursorObj.execute("select id, paymentdate , paymentvalue, car ,sellername from cars_buying_checks where nexttendays=?",(now,))
self.dashboard_buying_checks_dates_output = self.cursorObj.fetchall()
self.tenlistchecks.append(self.dashboard_buying_checks_dates_output)
print(self.tenlistchecks)
self.dashboard_buying_checks_dates = self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])
self.con.commit()
but I got an error :
[[(120, '21-08-2022', '1112', 'Alfa Romeo', 'james'), (122, '21-08-2022', '465', 'Buick', 'daniel '), (123, '21-08-2022', '789', 'Buick', 'daniel ')]]
self.dashboard_buying_checks_dates = self.cursorObj.executemany(
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 1 supplied.
self.cursorObj.fetchall() returns a list of tuples, which is what you need to feed to executemany, so
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",self.tenlistchecks)
not
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])

How to add multiple fields' reference to "unique_together" error message

I have a model with multiple fields being checked for uniqueness:
class AudQuestionList(BaseTimeStampModel):
aud_ques_list_id = models.AutoField(primary_key=True,...
aud_ques_list_num = models.CharField(max_length=26,...
aud_ques_list_doc_type = models.ForeignKey(DocType,...
short_text = models.CharField(max_length=55,...
aud_scope_standards = models.ForeignKey(ScopeStandard, ...
aud_freqency = models.ForeignKey(AuditFrequency, ...
aud_process = models.ForeignKey(AuditProcesses, ...
unique_together = [['aud_scope_standards', 'aud_freqency', 'aud_process',],]
My model form is as described below:
class CreateAudQuestionListForm(forms.ModelForm):
class Meta:
model = AudQuestionList
fields = ('aud_ques_list_doc_type', 'aud_scope_standards', 'aud_freqency', 'aud_process', 'short_text', ...
def validate_unique(self):
try:
self.instance.validate_unique()
except ValidationError:
self._update_errors({'aud_scope_standards': _('Record exists for the combination of key values.')})
The scenario works perfectly well, only that the field names (labels) itself are missing from the message.
Is there a way to add the field names to the message above, say something like:
Record exists for the combination of key fields + %(field_labels)s.

What is the problem in the following code?

I want to generate auto generate book fine of 10% of book cost. I have written the following code but nothing happens. No error comes and not working. book_cost field is in book module.
Please check code.
issue_date = fields.Date('Issue Date', required=True, tracking=True)
due_date = fields.Date('Due Date', required=True, tracking=True)
book_ids = fields.Many2many('odooschool.library.books','tch_book_rel','book_name','teacher_id','Issued Books')
sequence = fields.Integer('sequence')
fine_amount = fields.Char('Fine Amount', compute='_get_cost_details')
submission_date = fields.Date.today()
price = fields.Char('Price')
#api.depends('due_date','book_ids.book_cost')
def _get_cost_details(self):
market_multiplier = 0
date_return = fields.Date()
for rec in self:
fine_amount = 0
if rec.due_date and rec.submission_date and rec.due_date > rec.submission_date:
date_return = (rec.due_date - rec.submission_date)
market_multiplier = int(decimal.Decimal('0.10'))
fine_amount = rec.book_ids.book_cost * market_multiplier
rec.fine_amount += rec.fine_amount
I think if you replace
submission_date = fields.Date.today()
by
submission_date = fields.Date(default= fields.Date.today)
That will be work. Cause the submission_date in your code is always the starting date of Odoo server.
Regards

write attribute_line_ids in product.tempate in odoo 12

i am getting fields data from xls file and creating product
everything work fine except one2many field of variant in product.template
how can i achieve this.
here is my code.
main_product = self.env["product.template"].create(product_data)
attribute_ids = self.env["product.attribute"].search([])
attrib_id_set = set(ids.name for ids in attribute_ids)
product_attrib_ids = sheet.cell(suits, 13).value.split(",")
attrib_id_list = []; exist_attribute_list = []
for name in product_attrib_ids:
if name not in attrib_id_set:
attrib_id = self.env["product.attribute"].create({'name':name})
attrib_id_list.append(attrib_id)
else:
exist_attribute = self.env["product.attribute"].search([('name','=',name)])
exist_attribute_list.append(exist_attribute)
union_list = list(set(attrib_id_list).union(exist_attribute_list))
exist_attribute_values = self.env["product.attribute.value"].search([])
exist_attrib_val_list = [attrib_name.name for attrib_name in exist_attribute_values]
product_attrib_id_values = sheet.cell(suits, 14).value.split(",")
for value in product_attrib_id_values:
if value not in exist_attrib_val_list:
for ids in union_list:
attrib_value_id = self.env["product.attribute.value"].create({
'attribute_id':ids.id,
'name':value
})
main_product.write({
'attribute_line_ids':[(0,0,{
'attribute_id':ids.id, 'value_ids':(4,attrib_value_id.id)
})]
})
product_data is my dictionary for fields like name,sale_ok,type,catag_id etc.
this works, product is created, attribute_id and attribute values even works
but i can not write one2many of variant in product.template.
--EDIT--
values_lst=[]
for value in product_attrib_id_values:
if value not in exist_attrib_val_list:
for ids in union_list:
attrib_value_id = self.env["product.attribute.value"].create({
'attribute_id':ids.id,
'name':value
})
else:
for ids in exist_attribute_values:
if value == ids.name:
attrib_value_id =self.env["product.attribute.value"].browse(ids.id)
if attrib_value_id not in values_lst:
values_lst.append(attrib_value_id)

Python PonyORM One to one mapping

I am trying to create a one-to-one mapping using Pony ORM.
class ApplierIngress(ApplierObjectMapper.db.Entity):
correlation_id = orm.PrimaryKey(str)
ticket_number = orm.Required(str)
username = orm.Required(str)
status = orm.Required(str)
request_date = orm.Required(datetime)
class ApplierResult(ApplierObjectMapper.db.Entity):
correlation_id = orm.Required(ApplierIngress)
result = orm.Required(orm.LongStr)
request_date = orm.Required(datetime)
It throws error while generating the mapping
pony.orm.core.ERDiagramError: Reverse attribute for ApplierResult.correlation_id not found
I want correlation_id in ApplierResult table be the foreign key referencing to correlation_id in ApplierIngress table
Please let me know what am I doing wrong?
As error said you need to specify reverse attribute. Entities is not just Tables.
class ApplierIngress(ApplierObjectMapper.db.Entity):
correlation_id = orm.PrimaryKey(str)
ticket_number = orm.Required(str)
username = orm.Required(str)
status = orm.Required(str)
request_date = orm.Required(datetime)
result_id = orm.Optional('ApplierResult') # this attribute should be added
class ApplierResult(ApplierObjectMapper.db.Entity):
correlation_id = orm.Required(ApplierIngress)
result = orm.Required(orm.LongStr)
request_date = orm.Required(datetime)
Since this class is not yet declared you should use it as string or lambda
result_id = orm.Optional('ApplierResult')
result_id = orm.Optional(lambda: ApplierResult)
See here

Resources