2011-02-09 31 views
4

我有這樣的模式:不能排除ForeignKey的領域爲用戶在活塞

# models.py 
from django.contrib.auth.models import User 

class Test(models.Model): 
    author = models.ForeignKey(User, related_name="tests") 
    title = models.CharField(_("title"), max_length=100) 
在Django的web服務活塞的 api文件夾

然後:

class TestHandler(BaseHandler): 
    allowed_methods = ("GET") 
    model = Test 
    fields = ("title", ("author", ("username",))) 

    def read(self, request, id): 
     base = self.model.objects 
     try: 
      r = base.get(pk=id) 
      return r 
     except: 
      return rc.NOT_FOUND 

如果我把這個Web服務,然後我得到:

{ 
    "title": "A test" 
    "author": { 
     "username": "menda", 
     "first_name": "", 
     "last_name": "", 
     "is_active": true, 
     "is_superuser": true, 
     "is_staff": true, 
     "last_login": "2011-02-09 10:39:02", 
     "password": "sha1$83f15$feb85449bdae1a55f3ad5b41a601dbdb35c844b7", 
     "email": "[email protected]", 
     "date_joined": "2011-02-02 10:49:48" 
    }, 
} 

我也試過用exclude,但它也不管用。

我怎樣才能只爲author的用戶名? 謝謝!

+1

你的代碼看起來我的權利。其實,我知道,這將是令人沮喪,但我確切地複製你的榜樣,而我只得到了作者的用戶名,並在響應標題,完全按照自己的意圖。其餘用戶信息不顯示。 (你有嵌套是正確的,順便說一句。) – mjjohnson 2011-02-09 18:26:56

回答

2

好了,問題是,活塞用定義的字段集合在另一個Handler類的User模型上,而不是在這裏指定的嵌套字段。

另一個用戶指的是完全一樣的問題就在這裏,活塞討論組:

http://groups.google.com/group/django-piston/browse_thread/thread/295de704615ee9bd

的問題顯然是由活塞的序列化的代碼錯誤引起的。 在文檔的話:

通過在處理器使用模型,活塞會記住你的領域/排除的指示和誰返回該類型對象的其他處理器使用它們

(除非被覆蓋)。

哪個都好,除了「(除非被覆蓋)」情況似乎並沒有被正確地處理。

認爲,在emitters.py稍作修改可能會解決問題(線160-193)......

if handler: 
    fields = getattr(handler, 'fields')      
if not fields or hasattr(handler, 'fields'): 
    ...dostuff... 
else: 
    get_fields = set(fields) 

哪些應該(也許?)閱讀

if fields: 
    get_fields = set(fields) 
else: 
    if handler: 
     fields = getattr(handler, 'fields') 
    ...dostuff... 

如果你決定嘗試修補emitters.py,讓我知道如果這是訣竅 - 它應該是在django活塞中修補好的。

乾杯!

0

我覺得你不必要的嵌套的作者字段。

它看起來像你的領域屬性應改爲閱讀:

fields = ("title", "author", ("username",)) 

從活塞文檔...

class UserHandler(BaseHandler): 
     model = User 
     fields = ('name', 'posts', ('title', 'date')) 

will show the title and date from a users posts. 
+0

謝謝,但它並不能工作。我得到一個:「在/ api/test/1 /上的ValueError需要超過1個值才能解包」。我認爲我的方法是正確的。我正在閱讀活塞文檔和「配置處理程序」部分,他使用的數值幾乎與我使用的值相同。 – Menda 2011-02-09 16:54:28

+1

我不假設你也暴露了用戶上的處理程序?我猜可能活塞可能會用那個Handler的字段來代替。 (請參閱此帖子:http://groups.google.com/group/django-piston/browse_thread/thread/295de704615ee9bd)說了,我不能複製在該文章中提到的行爲,我也得到相同的正確響應,當我嘗試你的例子的時候,胡椒種植者。如果沒有,我想確保你有活塞的最新版本,以防現場處理現在已經修復了一些舊的錯誤... – 2011-02-10 00:40:54