Search code examples
databaseweb2py

web2py: Check if record in database?


example table:

db.define_table('pet',
    Field('name'),
    Field('owner_id','reference person'),
    Field('location_id','reference location'))

1) How can I check if there's a pet, called "Furry", owned by person 15 in location 26?

2) How can I check if there are any pets of person 8 in location 76? If so, return them.


Solution

  • Question 1

    db((db.pet.name == 'Furry') & (db.pet.owner_id == 15) & (db.pet.location_id == 26)).count()
    

    Question 2

    db((db.pet.owner_id == 8) & (db.pet.location_id == 76)).count()
    
    # if you have the name of the owner and the location you can even do 
    
    db((db.pet.owner_id == 
        db(db.person.name == 'NO_8_PERSON_NAME'
           ).select(db.persone.id).first().id) & 
       (db.pet.location_id == 
        db(db.location.location_name == 'NO_76_LOCATION_NAME'
           ).select(db.location.id).first().id)).count()