![](/img/trans.png)
[英]unable to access related objects with generic foreign key in Django and content types
[英]Django: foreign key access through related objects
假設我有一個通過與ForeignKey
unique=True
關系或OneToOne關系的ForeignKey
與標准User
模型相關的模型Profile
:
class Profile(models.Model):
user = (either a ForeignKey/OneToOne relationship)
...
如果我了解該文檔,則該列的數據庫表示形式為user_id
,來自Django,它會自動添加_id
。 該user_id將包含一系列整數。
再次假設我在外殼中實例化了該模型的對象,並嘗試訪問user
屬性:
a_profile = Profile()
a_profile.user
根據我的閱讀,在“ ForeignKey”關系的情況下, user
屬性現在應該是一個描述符,對其進行訪問將調用它的__ get __方法,從而使我可以訪問相關的模型實例-在這種情況下,用戶實例。
我的問題:
我注意到,我還可以通過具有OneToOne
關系的User實例通過以下方式訪問Profile實例:
user_profile = User.objects.all()[0]
user_profile.profile
當我做同樣的事情但是有一個ForeignKey
關系時,我得到一個查詢集。
幕后發生了什么? 而且,具有OneToOne
關系的Profile
實例上的user
屬性是否也是描述符,其工作方式與ForeignKey
關系一樣?
謝謝!
如果它們之間的關系是一對一的,則只能使用Object_X.user:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.