django - 通过外键实例获取表元素。

标签 django django-models

我在 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)

我是否需要将相关名称添加到作者外键字段才能获取结果?通过外键字段获取表行的正确方法是什么?

提前致谢。

最佳答案

只是为了澄清一件事,在这种情况下使用 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)

关于django - 通过外键实例获取表元素。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30753993/

相关文章:

python - 将 django sqlite 数据库迁移到 postgresql

python - 将 virtualenv 从 3.5.3 降级到 2.7

python - python(django)中的复杂 boolean 表达式

python - Django : Can we use . exclude() on .get() in django querysets

python - 值错误 : Field 'id' expected a number but got 'super' . [04/4/2020 18:15:11] "GET/super_user HTTP/1.1"500 132224

python - 自定义管理器并不总是为多对一关系添加计算字段

django - 在 django 中调用 create 时是否隐式调用了 save()?

django - 如何根据另一个查询集计算相关的多对多对象的计数?

python - 当 User 模型更新 Django 时,如何更新我的 UserProfile 模型

python - Django ORM - 将原始值分配给 DecimalField