select_related模型字段比较

时间:2015-12-28 21:38:37

标签: django database django-models django-rest-framework django-queryset

我已经在互联网上查了一下,但我很可能不知道要找的确切关键字。没有任何进一步的麻烦,问题。

我的模型大致如下所示:models.py

class Author(models.Model):
    author_book_count = models.IntegerField()
    author_name = models.CharField(max_length = 64)

class Book(models.Model):
    book_author = models.ForeignKey('Author')
    book_title = models.CharField(max_length = 128)
    book_serial_number = models.IntegerField()
    # Field above keep track of order in which book was written
    # value of 2 mean that it was second book author wrote and so on

在我的查询中,我可以轻松地执行以下操作

queryset = Author.objects.filter(author_name__icontains = "john").select_related('book')
return_data = queryset.filter(book__book_count = x).values('book__book_title')
# Gives me xth book of all authors in the queryset

问题:

我想了解作者的最新书籍,即author_book_count == book_serial_number,所以我应该在查询集中使用什么过滤器。

1 个答案:

答案 0 :(得分:0)

在这里和那里磕磕绊绊地尝试搜索术语的各种组合,我学会了F,它解决了我打算很好地解决的问题。方法大致如下。

return_data = queryset.filter(book__book_serial_number = F('author_book_count')).values('book__book_title')
相关问题