Python PonyORM One to one mapping - python-3.x

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

Related

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.

Many2many field tableundefined odoo, can't get multiple many2many fields

I have multiple Many2many fields but I'm getting the following error:
relation stream doesn't exist,undefined-table
I cannot find where this error is occurring. Can someone help me fix this error?
class College(models.Model):
_name = 'module5_college'
_description = 'College Info'
_rec_name = 'clg'
clg = fields.Char("College Name")
uni = fields.Char("Affiliated to")
cou = fields.Many2many('module5_stream',string="Stream")
class Stream(models.Model):
_name = 'module5_stream'
_description = 'Stream info'
_rec_name = 'cou'
cou = fields.Selection([
('BTECH', 'BTECH'),
('MTECH', 'MTECH'),
('MCA', 'MCA')],"Stream")
cou_mode = fields.Selection([
('Regular','Regular'),
('Lateral','Lateral'),
('Distance','Distance')],"Course Mode")
sem_no = fields.Integer("No of semesters")
# full_score = fields.Integer(compute='score_calc',string="Score")
sem = fields.Many2many('module5_sem',"Semesters")
class Semester(models.Model):
_name = 'module5_sem'
_rec_name = 'id'
sem_no = fields.Char("Semester No")
sub = fields.Many2many('module5_subject',"Subjects")
You have to follow this example because this is the way to create many2many field:
employees_ids = fields.many2many('Employees.Employees', 'tasks_employees_rel', 'task_id', 'employee_id', 'Employees assigned to task')
To give you a better example.
A employee can be assigned to many tasks
A task can be assigned to many employees
So you have a many2many relation, so that means that you have to create a new table containing both keys.

select on sub query peewee

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)

Acess Attributes from WX Forms

Given the following code Gist
I'm trying to use attributes from my parent class , but i can't access then.
src = BluTools.sourceFile.GetValue()
dest = BluTools.destFile.GetValue()
codigo_empresa = BluTools.codigo_empresa.GetValue()
codigo_deposito = BluTools.codigo_deposito.GetValue()
data = BluTools.data_inicio.GetValue()
But give-me error :
AttributeError: 'BluTools' object has no attribute 'sourceFile'
You need to read up on how classes work in Python. You do not normally access attributes by calling the class directly. You need to either create an instance of the class:
blue = BluTools()
blue.some_attr()
Or in your case, use self instead of BluTools
src = self.sourceFile.GetValue()
dest = self.destFile.GetValue()
codigo_empresa = self.codigo_empresa.GetValue()
codigo_deposito = self.codigo_deposito.GetValue()
data = self.data_inicio.GetValue()

Quering nested document query with Mongoengine

I have been trying to Query some mongo instances variables with python and MongoEngine
I need to get all the Variable from every RegistroPozo in all the Collection.
Example code:
from mongoengine import *
class Variable(EmbeddedDocument):
mnem=StringField(required=True, max_length=200)
description=StringField(max_length=500)
unit=StringField( max_length=200,default='ppm')
alias=StringField( max_length=200) #,default=mnem
type=StringField( max_length=200,default='DEPENDANT')
class RegistroPozo(EmbeddedDocument):
fecha = DateTimeField()
filepath = StringField()
start = FloatField()
step = FloatField()
stop = FloatField()
variables = EmbeddedDocumentListField(Variable)
registros = ListField(DictField())
version_information_block = StringField(max_length=500)
well_information_block = StringField(max_length=500)
curve_information_block = StringField(max_length=500)
parameter_information_block = StringField(max_length=500)
other_block = StringField(max_length=500)
class Pozo(DynamicDocument):
uwi_pozo = StringField(required=True, max_length=200, primary_key=True)
nom_pozo = StringField(required=True, max_length=200)
prof_total = FloatField(required=True)
elev_terr = FloatField(required=True)
long_pozo = FloatField(required=True)
lat_pozo = FloatField(required=True)
coord_x_po = FloatField(required=True)
coord_y_po = FloatField(required=True)
registros_pozo=EmbeddedDocumentListField(RegistroPozo)
When I try to query I make a lot of loops, but I belive there is a better way to do it.
Something like:
variables_in_all_the_doc = Pozo.objects(Q(AdvanceQuery))
Pozo is a single document at mongo db level. Embeded document are just mongoengine constructs. So when you read Pozo objects, all embedded documents are also available in the same query (check with mongostat). Now iterating on this data is not a big concern. For advanced EmbeddedDocumentList queries please read the docs here.

Resources