开发者

How to queryset all user that are in a foreign table?

I have a model called book and in that model there is a foreignkey field (called author) to the user model.

I need in one of my views to returm a list of all the authors(not all users, just users that appear in the book model(just the authors).

I don't know why, but i'm having开发者_如何学编程 a hard time getting that.

Can any one please help me with this?

10x,

Erez


Try this:

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

I'm assuming there is only one foreign key from the Book model to the User model.

  • isnull filters for all users which are in the which are linked to the Book model.
  • distinct ensures that each author only appears once in the results.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜