Django 查询包括加入

时间:2021-02-12 15:00:02

标签: django django-models django-rest-framework django-views

我试图计算与产品相关的竞争对手产品价格的增加和减少的数量。我无法应付。我可以通过覆盖 get_context_data 方法来做到这一点吗?我无法编写查询来从 comp_product 模型中获取数据。我该如何处理?

型号:

class Product(models.Model):
    user       = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products')
    category   = models.CharField(max_length=120)
    brand      = models.CharField(max_length=120)
    product    = models.CharField(max_length=120)
    price      = models.DecimalField(decimal_places=2,max_digits=100)

class Comp_Product(models.Model):
    product     = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products")
    competitor  = models.URLField()
    price       = models.DecimalField(decimal_places=2,max_digits=100)
    change      = models.FloatField()
    stock       = models.BooleanField()
    last_update = models.DateField(auto_now_add=True)

查看:

class DashboardList(ListView):

    template_name='dashboard_by_user.html'

    def get_queryset(self):
        p = Product.objects.filter(user=self.request.user)
        return p

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        Products = context['object_list']
        context['distinct_category_count'] = Products.values('category').distinct().count()
        context['distinct_brand_count']    = Products.values('brand').distinct().count()
        context['product_count']           = Products.values('product').count()
        context['num_comp_products_with_lower_price'] = p.comp_products.filter(price__lt=p.price).count()
        context['num_comp_products_with_higher_price'] = p.comp_products.filter(price__gt=p.price).count()

        return context

1 个答案:

答案 0 :(得分:0)

如果我假设您想为 Product p 检索具有较低或较高 Comp_Product 的竞争对手产品 price 的数量,那么这将使您开始:

# This is the product you're looking at, it'll be retrieved
# via the queryset and it's just randomly the first.
# If you want to do this for all products in the queryset
# you'll need to work with annotate.
p = self.queryset.first()
num_comp_products_with_lower_price = p.comp_products.filter(price__lt=p.price).count()
num_comp_products_with_higher_price = p.comp_products.filter(price__gt=p.price).count()

如果您的视图中有 p,那么在 get_context_data 中执行此操作应该没有问题。

相关问题