2012-01-21 120 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

相關問題