猿问

Django 反向 m2m 查询

使用https://docs.djangoproject.com/en/dev/topics/db/queries/#making-queries 中的模型并稍作修改:


from django.db import models


class Blog(models.Model):

    name = models.CharField(max_length=100)


class Author(models.Model):

    name = models.CharField(max_length=200)

    joined = models.DateField()


    def __str__(self):

        return self.name


class Entry(models.Model):

    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

    headline = models.CharField(max_length=255)

    authors = models.ManyToManyField(Author)

    rating = models.IntegerField()

我想创建一个从作者到条目的字典,作者今年加入,条目的评分为 4 或更高。结果字典的结构应如下所示:


author_entries = {author1: [set of entries], author2: [set of entries], etc.}

而访问数据库的次数少于 3 次(或至少与作者或条目的数量不成正比)。


我的第一次尝试(db hits == 作者数量,100 个作者 100 db-hits):


    res = {}

    authors = Author.objects.filter(joined__year=date.today().year)


    for author in authors:

        res[author] = set(author.entry_set.filter(rating__gte=4))

第二次尝试,尝试一次性阅读条目:


    res = {}

    authors = Author.objects.filter(joined__year=date.today().year)

    entries = Entry.objects.select_related().filter(rating__gte=4, authors__in=authors)


    for author in authors:

        res[author] = {e for e in entries if e.authors.filter(pk=author.pk)}

这个更糟,100 个作者,198 个 db-hits(最初使用的第二次尝试{e for e in entries if author in e.authors},但 Django 没有它。


我发现的唯一方法涉及 raw-sql(4 db-hits):


    res = {}

    _authors = Author.objects.filter(joined__year=date.today().year)

    _entries = Entry.objects.select_related().filter(rating__gte=4, authors__in=_authors)

    authors = {a.id: a for a in _authors}

    entries = {e.id: e for e in _entries}

    c = connection.cursor()

    c.execute("""

        select entry_id, author_id 

        from sampleapp_entry_authors

        where author_id in (%s)

    """ % ','.join(str(v) for v in authors.keys()))


(对于在c.execute(..)调用中使用字符串替换表示歉意——我找不到where in ?调用所需的语法 sqlite )。


有没有更 Djangoesque 的方式来做到这一点?


我用我正在使用的代码(https://github.com/thebjorn/revm2m)创建了一个 git repo ,测试在https://github.com/thebjorn/revm2m/blob/master/revm2m/示例应用程序/tests.py


莫回无
浏览 99回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答