我正在尝试在我的Django视图中生成get_queryset
结果,其中ProductDetails
模型与每个产品的价格模型中的最低价格合并。
class ProductDetail(models.Model):
productId = models.AutoField(primary_key=True, editable=False)
brandId = models.ForeignKey('brands.Brand')
class Price(models.Model):
storeId = models.ForeignKey('Store')
productId = models.ForeignKey('ProductDetail')
price = models.DecimalField('Price', max_digits=10, decimal_places=2)
storePriceUrl = models.CharField('Product url', max_length=300)
inStock = models.BooleanField('In stock', default=True)
class Store(models.Model):
storeId = models.AutoField(primary_key=True, editable=False)
storeText = models.CharField('Store', max_length=100)
storeSlug = models.SlugField(max_length=100)
storeURL = models.CharField('URL', max_length=100, default='http://')
storeImage = models.FileField(upload_to='stores/storelogos/')
class Products(generic.ListView):
template_name = 'products.html'
context_object_name = 'product_list'
def get_queryset(self):
pdlist = ProductDetail.objects.select_related().all()
pricelist = Price.objects.filter().values_list('productId_id').annotate(Min('price')).order_by('price')[0]
result_list = itertools.chain(pdlist, pricelist)
return result_list
我正在尝试从每个产品的价格模型中以最低价格(和相关详细信息)获取所有与产品相关的数据。请注意,我只有几个星期进入Django所以仍然在学习绳索。 感谢您提前提供任何帮助。
答案 0 :(得分:0)
将您的productId
字段更改为:
productId = models.ForeignKey('ProductDetail', related_name='prices')
然后使用以下查询:
pdlist = ProductDetail.objects.annotate(min_price=Min('prices__price'))\
.order_by('min_price')