【问题标题】:django : get object from foreign keydjango:从外键获取对象
【发布时间】:2012-12-23 13:17:30
【问题描述】:

假设以下模型类,

 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')

如何从owner 对象中获取sitter 对象?

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

UserProfile.objects.filter(bookmarkOwner=user)

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

【问题讨论】:

    标签: django model


    【解决方案1】:

    如果你想避免使用循环,我相信你可以这样做:

    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/2.0/ref/models/fields/#manytomanyfield

    【讨论】:

    • sitters = UserProfile.objects.filter(pk__in=pks).all()末尾不需要.all()
    • 绝妙的答案!另外,我使用这种方法是因为我无法轻松地更新 ManyToMany 字段
    【解决方案2】:

    你应该这样做

    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
    

    如果用户配置文件只有一个 Bookmark 对象(没有多个条目)。那么你应该改用.get 方法(它返回一个对象)。

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

    【讨论】:

    • 谢谢。但是还有其他不使用 for 循环的方法吗?
    • 书签表是否只包含一个与profile相关的Bookmark对象?
    • 是的,父母可以有很多书签,保姆可以有很多书签,但是对于一个父母 - 一对保姆,只有一个书签
    • 请查看我的更新答案how to retrieve a single object。对于一对父母一对保姆,您应该这样做Bookmark.objects.get(owner=user, sitter=other_user)
    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 2018-12-01
    • 1970-01-01
    • 2013-12-28
    • 2017-10-03
    • 2017-10-18
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多