2012-01-21 66 views
1

我是GAE中的新成员,所以如果您想帮忙,请写下一些详细信息和示例。在Google应用程序引擎中设计数据库

我想要做两个db模型,用户和文章。每个用户可以有一些文章。在SQL Server中这将是:

create table User 
(
    id int primary key identity(1,1), 
    login nvarchar(50) unique not null, 
    password nvarchar(50) not null, 
    email nvarchar(50) unique not null, 
) 

create table Article 
(
    userId int references User(id) not null, 
    topic nvarchar(50) not null, 
    content nvarchar(max) not null 
) 

在Python中我尝试:

class Article(db.Model): 
    topic = db.StringProperty(multiline=False) 
    content = db.StringProperty(multiline=True) 

class User(db.Model): 
    login = db.StringProperty() 
    email = db.EmailProperty() 
    password = db.StringProperty(multiline=False) 
    articles = db.ListProperty(int) #here I want to do db.ListProperty(Article), but I can't. So I want to keep here id of article. 

而且我的问题是:

  • 我怎么能提供登录和电子邮件将是独一无二的
  • 我如何获得用户的主键(在sql

    select id from User where login = 'sada' and password = 'sd' 
    
  • 我如何使用这个主键搜索用户
  • 我怎么能增加对用户新的文章,如果我想保持ID的用户文章

也许这是一些更好的方式来做到这很喜欢我会知道更好的解决方案

回答

3

首先Google AppEngine Datastore不是关系数据库。这是一个完全不同的范例。也许你应该先看看Datastore Overview documentationMastering the datastore

关于你提到的具体问题:

  1. 唯一的登录和电子邮件:你必须检查它不已经存在,因为数据存储区不提供独特的约束上。你也可以看看这个解决方案:Add a Unique Constraint to Google App Engine。或者你可以使用Google Accounts
  2. 为用户主键搜索用户主键:使用谷歌AppEngine上,你会得到直接的用户:user = db.GqlQuery("SELECT * FROM Users WHERE login IS :1", login)
  3. 参考:这里是一个关于它的非常好的文章:Modeling entity relationships
1
  1. 在数据存储中没有唯一的限制。唯一保证唯一的财产是实体的关键(key_name)。您可以将登录名和电子邮件组合在一个字符串中,并将其用作key_name。这当然会限制更改登录和密码的可能性(您需要创建一个新实体并重写引用)。

  2. 使用此代码(keys_only意味着只有一键返回,而不是整个实体)

    query = db.Query(User, keys_only=True) 
    query.filter('login =', 'sada') 
    query.filter('password =', 'sd') 
    user_key = query.get() 
    
  3. 喜欢这个

    db.get(user_key) 
    

    ,如果你没有一个按键,创建一个:

    user_key = Key.from_path(User, id_or_name) 
    
  4. 有几种方法做到这一点。阅读关于data modeling

相关问题