开发者

Many-to-many relationships in Django - mysql's ISNULL() equivalent

I have two models that are basically this:

Book(Model):
    title = models.CharField(max_length = 250)
    read_by = ManyToMa开发者_高级运维nyField(User)
    ...  

User(Model):
    firstName = models.CharField(max_length = 250)
    lastName = models.CharField(max_length = 250)
    ...

Now, how do I create a list of all books with a "read" boolean for each book? In mysql I can use a ISNULL() with a OUTER JOIN. How can I do this in Django? Do I have to use raw mysql?

Clarification: I want to create the list for each user, so that each user can "tick off" each book they've read.


books = Book.objects.annotate(read=models.Count('read_by'))

Then if you want a list of read books only::

read_books = books.exclude(read=0)

Or you can just use the read annoteted property of each instance which, being an integer, will obviously evaluate to the correct boolean value for unread books.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜