django:从外键获取对象 [英] django : get object from foreign key
本文介绍了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')
我如何从 owner
对象中获取 sitter
对象?
How can I get sitter
objects from owner
Objects?
user = UserProfile.objects.get(pk=1)
UserProfile.objects.filter(bookmarkOwner=user)
返回空的 tuple
,我无法指定 sitter
变量.
returns empty tuple
, and I cannot specify sitter
variable.
推荐答案
如果您想避免使用循环,我相信您可以执行以下操作:
I believe you can do something like this, if you want to avoid using a loop:
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
Alternatively, you might want to experiment with setting up a many-to-many field and using the through
parameter. See the Django docs: https://docs.djangoproject.com/en/2.0/ref/models/fields/#manytomanyfield
这篇关于django:从外键获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文