通过外键实例获取 table 的元素。

Get element of table by instance of foreign key.

我在 Django 中有两个模型:

class Blog(models.Model):

   author = ForeignKey(Author)
   post = models.CharField(max_length=100)

class Author(models.Model):
   name = models.CharField(max_length=100)

我需要按作者的实例获取博客条目:

author_one = Author (name ='John')
author_one.save()
blog_entry = Blog.objects.get(author = author_one)

是否需要在 Author Foreignkey 字段中添加相关名称才能获得结果?通过外键字段获取 table 行的正确方法是什么?

提前致谢。

您可以通过以下方式访问相关数据:

author_one.blog_set

参考:Django docs: Related objects

不需要指定一个related_name,但是如果你指定了,那么你可以类似地使用它,例如:

class Blog(models.Model):
   author = ForeignKey(Author, related_name='author_blogs')
...
author_one_blogs = author_one.author_blogs.all()

参考:Django 文档:Foreign key related_name, Following relationships backward

只是为了澄清一件事,在这种情况下使用 get() 是不正确的,引用 get() 文档 :

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly

或者Wtower提到的,你也可以使用:

blog_entry = Blog.objects.filter(author=author_one)

Please check the get query,

change this from

blog_entry = Blog.objects.get(author = author_one)

to

blog_entry = Blog.objects.get(author=author_one)

Because "=" doesn't take spaces when extracting object.