Aaron Wheeler
Aaron Wheeler

Reputation: 703

How should I serialize / reference App Engine users?

This is a follow-up to this question:

How do I correctly reference Users in GQL queries on App Engine?

In my app, I have a Photos db.Model, where each photo has a UserProperty. I want to display a list of users, where clicking on a user will show all of the user's photos.

What is the best way to reference the user when creating a link to the user's photo page?

I've found two options, both which have their shortcomings.

  1. user.nickname() - this can be used in a GQL query (e.g. Photos.gql("WHERE user = USER(:1)", user.nickname()) ), but it can change, it's not necessarily unique, and sometimes (e.g. for Gmail addresses) user.nickname() truncates at the '@' symbol and can't be used for lookups without appending "@gmail.com".
  2. user.user_id() - this is unique, but I haven't found a way to lookup a user by the user_id()

Is there a better way to do this? Currently, I'm storing both the user and the user_id() on the Photo model, doing a GQL search by user_id passed in the link, and then referencing the user from the UserProperty on the Photo model.

Upvotes: 2

Views: 199

Answers (2)

Abdul Kader
Abdul Kader

Reputation: 5842

I think the best way is to pass the user_id as the key_name and use get_or_insert()

import models
from google.appengine.ext import db
from google.appengine.api import users
class Photo( db.Model ):
    owner = db.UserProperty()
    title = db.StringProperty()

photo = Photo(key_name=users.get_current_user().user_id())
photo.owner=users.get_current_user()
photo.title= 'hai'
photo.put()
user_id = users.get_current_user().user_id()

photo = Photo.get_or_insert(user_id)

Upvotes: 2

Nick Johnson
Nick Johnson

Reputation: 101149

Use the user_id. 'looking up' a user isn't really a meaningful operation unless you mean to get their email address and/or nickname. You should have a users table that stores User objects, keyed by the user_id, along with any other site-specific information you need on them (eg, preferences, profile information).

Upvotes: 3

Related Questions