通过外键django过滤对象queryset

时间:2013-12-20 04:52:48

标签: django python-2.7 foreign-key-relationship django-queryset

我收到了这段代码

class Author:
    data1 = models.CharField(max_length=200)

class Book:
    author = models.ForeignKey(Author)

如何过滤至少有一本图书参考书的作者? 我在django 1.6上 Python 2.7

提前致谢

2 个答案:

答案 0 :(得分:2)

你可以做到

Auther.objects.filter(book__isnull=False).distinct()

答案 1 :(得分:0)

book = Book.objects.get(id=1) # a book instance
author =  book.author_set.all()   #all  Author from book
author.filter(data1='xxx') #filter 

for i in author:
    print i. data1    # i is Author instance