2017-07-06 128 views
-1

我嘗試篩選具有特定類別的Book類的作者,但無法獲得確切的類別。兩個表格篩選器

models.py

class Book(models.Model): 
    category = models.CharField() 
    foreignkey = models.ForeignKey(Author, related_name="auth") 
class Author(models.Model): 
    author_id = models.IntegerField(primary_key=True) 

views.py

book = models.Book.objects.filter(category = 'Space') 
author = models.Author.objects.filter(author_id__in = book) 
+0

'book = models.Book.objects.filter(category ='Space')'但是您的Book類中的類別是'models.IntegerField()'。可以過濾'category = '或將類別更改爲'models.CharField()'。另外,你用你的作者過濾器試着做什麼? – Bott0610

+0

對不起,我舉了一個錯誤的例子。 – max

回答

0
class Book(models.Model): 
    category = models.CharField() 
    author = models.ForeignKey(Author, related_name='books') 

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


books = Book.objects.values('author_id',flat=True).filter(category='Space') 
authors = Author.objects.filter(pk__in=books) 
0
class Book(models.Model): 
    category = models.CharField() 
    author = models.ForeignKey(Author, related_name='books') 

class Author(models.Model): 
    # pks are added automatically 

在views.py

books = models.Book.objects.filter(category='Space') 
authors = models.Author.objects.filter(pk__in=[b.author_id for b in books]) 
+0

'書'沒有屬性名稱id,我修改它爲'b.author'仍然不起作用。 – max