[英]Get Foreign Key parent of object - Django
Suppose I got two models like this: 假设我有两个这样的模型:
class Article(models.Model):
article_title = models.CharField(max_length=100)
class EventRecord(models.Model):
article = models.ForeignKey(Article)
In a view, I select a certain EventRecord and want to show the Title of the Article it is related to as well. 在视图中,我选择某个EventRecord并希望显示与其相关的文章标题。 The following does not work: 以下内容不起作用:
def classify(request, pk):
event = get_object_or_404(EventRecord, pk=pk)
article_id = event.article
article = get_object_or_404(Article, pk=article_id)
How do I make this work? 我该如何工作? Any help is really appreciated! 任何帮助都非常感谢!
Django automatically handles this for you. Django会自动为您处理。 For example: 例如:
>>> record = EventRecord.objects.get(...)
>>> isinstance(record.article, Article)
True
>>> record.article.article_title
u'title here'
This is one of the magical things Django does (nothing is magic but anyway...). 这是Django所做的神奇的事情之一(反正什么都不是神奇的……)。 Please keep in mind that in order for this work Django will usually execute some extra database queries. 请记住,为了完成这项工作,Django通常会执行一些额外的数据库查询。 To eliminate them, you can use select_related
method. 要消除它们,可以使用select_related
方法。 Below is a snippet which eliminates extra queries and does what you want: 下面是一个片段,它消除了额外的查询,并且可以满足您的需求:
def classify(request, pk):
record = EventRecord.objects.filter(pk=pk).select_related()
# the above returns queryset hence you have to extract the record manually
if not len(record):
raise Http404()
else:
record = record[0]
# now use record as usual and no extra queries will be executed
title = record.article.article_title
...
event.article
returns the actual Article
object, not the primary key, so you don't need to do another database query. event.article
返回实际的Article
对象,而不是主键,因此您无需执行其他数据库查询。
def classify(request, pk):
event = get_object_or_404(EventRecord, pk=pk)
if not event.article:
raise Http404
print event.article.article_title
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.