从单个对象开始预取相关 - 在第二次预取和计数和顺序中获得第一个



我有3种型号产品,公司类别。

class Product(Meta):
    categories = models.ManyToManyField(Category)
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)

我需要:

  • 获得公司的所有产品
  • 显示产品第一类
  • 计算每个公司的数量产品并显示
  • 通过反向更新订购产品

我从:

开始
1. Company.objects.get(pk=company_pk).prefetch_related('products')

会给我一个错误,因为获得返回对象:

class CompanyProductListView(ListView):
 model = Company
 template_name_suffix = '_company_list'
def get_queryset(self):
    company_pk = self.kwargs.get('pk')
    return Company.objects.get(pk=company_pk).prefetch_related('products')

无需预摘要。

  1. return Company.objects.filter(pk=company_pk).prefetch_related('products')

没有错误,但是在模板中:

 {% for company in company_list %}
        {{ company.name}}
    {% endfor %}

我循环甚至是一个,但没有给我任何东西。

除此之外,我需要将第一个类别附加到每种产品上,并计算产品数

我正在考虑访问这样的东西:

{{company.name}}
{% for product in company.products %}
   {{ product.name }}
   {{ product.category }}

此查询会变得有些复杂,但应该帮助您解决问题。

ps:我尚未对此进行测试,但主要应该起作用。一旦我有更多的时间,就会更深入地看待。

首先,我们得到想要的公司:

company = Company.objects.get(pk=company_pk)

然后,我们获取所有产品的所有第一类,可以通过将此问题作为指导来完成:

first_categories = Category.objects.order_by('product__id', '-id').distinct('product__id')

现在,我们使用第一个_categories来限制我们预取的数据量(给出不同的视角,我们将查询Product模型而不是Company模型)

product_list = Products.objects.filter(company=company).prefetch_related(
    Prefetch('categories', queryset=first_categories)
)

def get_queryset():
    company_pk = ...
    company = ...
    first_categories = ...
    product_list = ...
    return product_list

最新更新