John Doe
John Doe

Reputation: 1639

web2py : non identical field constraint

I would like to define the following table with a non identical field value as a follower should not follow himself :

db.define_table('followers', 
    Field('follower', 
          db.auth_user, 
          requires=(db.subscription.follower != db.subscription.user)),
    Field('user', 
          db.auth_user, 
          requires=(db.subscription.follower != db.subscription.user))
)

But I don't know how to implement it. Any hint ?

Thank you

Upvotes: 0

Views: 30

Answers (1)

Anthony
Anthony

Reputation: 25536

Assuming inserts will happen via form processing:

db.define_table('followers', 
    Field('follower', 'reference auth_user',
          requires=IS_IN_DB(db(db.auth_user.id != request.post_vars.user),
                            'auth_user.id', db.auth_user._format)),
    Field('user', 'reference auth_user'))

This will allow any auth_user ID in the user field, but will limit the follower field to IDs other than the one submitted in request.post_vars.user. When there is no form submission, request.post_vars.user will simply be None, which doesn't matter because the validator is used only upon form submission.

Alternatively, you can use an onvalidation callback function when processing the form.

Upvotes: 1

Related Questions