简体   繁体   English

Django多对多字段:Queryset值

[英]Django many to many field : Queryset values

I have the following in django 1.8 : 我在django 1.8中有以下内容:

class Author(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    @property
    def full_name(self):
        return u"{0} {1}".format(self.first_name, self.last_name)

class Article(models.Model):
    title = models.CharField(max_length=10, unique=True)
    authors = models.ManyToManyField(Author)

I would like to get a queryset that has the following format: 我想要一个具有以下格式的查询集:

results = [{"title":"title1","authors":['first_name last_name', 'first_name last_name']

So all the many_to_many objects are grouped into a list. 因此,所有many_to_many对象都分组为一个列表。

The query i'm used to perform for these cases is : 我用于这些情况下执行的查询是:

results = Article.objects.all().prefetch_related('authors').values('title','authors')

I can solve the issue by looping into each object and constructing a new dictionary, but it becomes a bottleneck after +100 items. 我可以通过循环到每个对象并构造一个新字典来解决此问题,但是在+100个项目之后,它成为了瓶颈。

    results = []
    for element in Article.objects.all().prefetch_related('authors'):
        results.append(dict(title=element.title, 
authors=[b.full_name for b in element.authors.all()]))

Is there a django way to solve this issue ? 有django解决此问题的方法吗?

Something I would try is the following: 我会尝试以下操作:

results = []
authors = Author.objects.only('full_name')
qs = Article.objects.only('title').prefetch_related('authors', queryset=authors)
for element in qs:
    results.append(
        dict(
            title=element.title, 
            authors=[b.full_name for b in element.authors.all()]
        )
    )

OR 要么

results = []
qs = Article.objects.select_related('authors').only('title', 'author__full_name')
for element in qs:
    results.append(
        dict(
            title=element.title, 
            authors=[b.full_name for b in element.authors.all()]
        )
    )

This basically amounts to reducing the amount of data fetched from the server by querying only the required columns and then trying select_related instead of prefetch_related (whether this helps or not depends heavily on the your actual data). 从根本上讲,这仅是通过查询所需的列,然后尝试使用select_related而不是prefetch_related来减少从服务器获取的数据量(这是否在很大程度上取决于您的实际数据)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM