Add a custom column in SQLFORM.grid that counts rows in child table

63 views
Skip to first unread message

Mamisoa Andriantafika

unread,
Oct 18, 2015, 1:26:07 PM10/18/15
to web2py-users
Hi,

I have a model like this:

db.define_table('patient',
   
Field('name','string'),
   
Field('first_name','string'),
   
Field('dob','date'),
   
Field('disease','string', requires=IS_NOT_EMPTY()))

db
.define_table('injection',
   
Field('id_patient', 'reference patient', writable = False, readable = False),
   
Field('date_iiv', 'date'),
   
Field('product','string'))


I'd like to use SQLFORM.grid to display in addition to all fields an extracolumn counting the number of injections i.e:

Name / First Name / dob / disease / NUMBER of INJECTIONS

the number of injection being count for each row with this query:

count_iiv = db(db.injection.id_patient == db.patient.id ).count()

How can I include that in the SQLFORM.grid definition?

Thanks,

Mike


Mamisoa Andriantafika

unread,
Oct 18, 2015, 3:47:03 PM10/18/15
to web2py-users
I managed it by using older answers on post:

https://groups.google.com/forum/#!searchin/web2py/grid$20virtualfield/web2py/tTWYuhhGr8I/mObd5LPkci4J

creating a function and a virtual field in the model :


def get_iiv_number(id_patient):
    count_iiv
= db((db.iiv.id_patient == id_patient)).count()
   
return count_iiv

db
.patient.count_iiv = Field.Virtual('count_iiv',lambda row: get_iiv_number(row.patient.id))

Reply all
Reply to author
Forward
0 new messages