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