2012-12-23 55 views
0

假設下的模型類獲取對象,Django的:從外鍵

class Bookmark(models.Model): 
    owner = models.ForeignKey(UserProfile,related_name='bookmarkOwner') 
    parent = models.ForeignKey(UserProfile,related_name='bookmarkParent') 
    sitter = models.ForeignKey(UserProfile,related_name='bookmarkSitter') 

我怎樣才能得到sitter對象從owner對象?

user = UserProfile.objects.get(pk=1) 

UserProfile.objects.filter(bookmarkOwner=user) 

返回空tuple,我不能指定sitter變量。

回答

2

我相信你可以做這樣的事情,如果你想避免使用循環:

pks = some_user_profile.bookmarkOwner.values_list('sitter', flat=True) 
sitters = UserProfile.objects.filter(pk__in=pks).all() 

或者,你可能想建立以實驗了許多一對多場使用through參數。請參閱Django文檔:https://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield

+0

在'sitters = UserProfile.objects.filter(pk__in = pks).all()'末尾不需要'.all –

1

你應該做的

objs = Bookmark.objects.filter(owner=user) 
# This will return all bookmarks related to the user profile. 

for obj in objs: 
    print obj.owner # gives owner object 
    print obj.parent # gives parent object 
    print obj.sitter # gives sitter object 

如果只有一個用戶配置文件(沒有多個條目)收藏對象。然後,您應該使用.get方法(返回單個對象)。

obj = Bookmark.objects.get(owner=user) 
print obj.owner 
print obj.parent 
print obj.sitter 
+0

謝謝。但是,有沒有其他方式不使用循環? –

+0

書籤表是否只包含一個與配置文件相關的Bookmark對象? –

+0

是的,父母可以有很多書籤,可以有多個書籤,但是對於一個父母 - 一個保姆對,只有一個書籤 –