高效查询django Query

问题描述 投票:0回答:1

我们正在与 django 一起制作报纸。在进一步阅读之前,让我向您展示代码。

    # Fetch lead, top, and other filtered news
    news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id')
    lead = news_objects.filter(status='lead').order_by('-published_date').first()
    top = news_objects.filter(status='top').order_by('-published_date')[:4]
    filtered_news = news_objects.exclude(status__in=['lead', 'top']).order_by('-published_date')

    # Fetch filtered categories and prefetch limited news related to filtered categories
    categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related(
        Prefetch('catagory', queryset=filtered_news, to_attr='limited_news')
    )

    # Limit the news to the first 5 for each category
    for category in categories_with_news:
        category.limited_news = category.limited_news[:6]`

下面的代码将获取特定域中的所有新闻。新闻内容超过10k

news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id')

下面的代码只会从 news_objects 获取 5 条新闻


lead = news_objects.filter(status='lead').order_by('-published_date').first()
top = news_objects.filter(status='top').order_by('-published_date')[:4]

下面的代码将获取将显示在前面的所有类别及其数据。

categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related(
        Prefetch('catagory', queryset=filtered_news, to_attr='limited_news')
    )

下面的代码将再次获取每个类别 6 条新闻。

for category in categories_with_news:
        category.limited_news = category.limited_news[:6]

我的问题是我不认为获取所有新闻是个好主意,因为我不需要超过 60 条新闻。如何高效地做到这一点。

我尝试将查询限制为 300,但也可能存在问题,在某些类别中,第 6 个可能位于 350 的位置。

django django-views django-4.0
1个回答
0
投票

一些事情:

  1. 不要迭代
    categies_with_news
    ,在实际需要时调整限制(例如序列化/响应时间)。
  2. 请勿使用
    __in=[True]
    ,而仅使用
    =True
  3. 确保您索引
    status
    published_date
    website
  4. 确保您的回复已分页。

#1 是你最大的杀手。

对于此类查询 <10million records your response times should be around .2 +-.1s or so.

© www.soinside.com 2019 - 2024. All rights reserved.