Joe T. Boka
Joe T. Boka

Reputation: 6581

One to many relation Web2py

This is my Model:

db.define_table('person',
                    Field('name'),
                    format='%(name)s')
db.define_table('thing',
                    Field('name'),
                    Field('owner_id', 'reference person'),
                    format='%(name)s')

This is the Controller:

def ref():
    rows = db(db.person.id==db.thing.owner_id).select()
    return locals()

This is the View:

{{for row in rows:}}
<h1>{{=row.person.name}}</h1><h3>{{=row.thing.name}}</h3>
{{pass}}

I am able to use a join here and loop over all persons and fetch their things.

My question is: how can I randomly select one person and fetch that person's things only?

I have tried several different ways to achieve this but I am obviously missing something. I would appreciate some guidance with this.

Upvotes: 0

Views: 100

Answers (1)

Rockbot
Rockbot

Reputation: 973

This might not be beautiful, but try:

def function():
    from random import randint
    persons = db(db.person.id > 0).count()
    rand = randint(1, persons)
    the_person = db.person(rand)
    persons_things = db(db.thing.owner_id == rand).select()
    for thing in persons_things:
        print thing
    return dict(the_person=person, persons_things=things)

The view:

<h1>{{=person.name}}´s Things:</h1>
<p>
    {{=for thing in things:}}
        {{=thing.name}}
    {{pass}}
    </br>
</p>

Upvotes: 1

Related Questions