从2个表django中检索信息

时间:2014-07-24 21:05:20

标签: django

我正试图从django的第二张表中获取信息,但无法使其正常工作......

MYSQL中的查询就像这样......

SELECT search_products.model, search_products.year, search_products.size, search_avg_price.estimated_price
FROM search_products
left JOIN search_avg_price
ON search_products.model=search_avg_price.model and search_products.size=search_avg_price.size and search_products.year=search_avg_price.year

我有一张桌子,其中包含一系列具有3个特征的产品:型号,尺寸和年份。

在另一张桌子上,我有每种型号,尺寸和年份组合的平均价格。

我想从表avg_price中检索estimated_price字段,以便在我的模板上使用它以及products表中的字段。

一切正常但我没有从表avg_price获得该字段的任何结果,只有product表中的字段......

我的模型(我希望他们加入三个领域:模型,大小和年份。不确定我是否正确完成,因为我没有在任何地方指定它):

class Avg_price(models.Model):
 model = models.CharField(max_length=50, blank=True)
 size= models.IntegerField(blank=True, null=True)
 year= models.IntegerField(blank=True, null=True)
 estimated_price= models.IntegerField(blank=True, null=True)

class Products(models.Model):
 product_id =models.IntegerField(blank=True, null=True)
 link_id = models.CharField(max_length=200, blank=True)
 location = models.CharField(max_length=200, blank=True)
 model = models.CharField(max_length=50, blank=True)
 size= models.IntegerField(blank=True, null=True)
 price= models.IntegerField(blank=True, null=True)
 year= models.IntegerField(blank=True, null=True)
 type=models.ForeignKey(Type)
 avg_price = models.ForeignKey(Avg_price)

 def __unicode__(self):  # Python 3: def __str__(self):
   return self.location

我的观点

def index(request):

latest_products = Products.objects.all().prefetch_related("avg_price")

if request.POST.get('modelo') is not None and request.POST.get('modelo') != "":
    latest_products = latest_products.filter(model=request.POST.get('modelo'))

template = loader.get_template('search/index.html')
context = {'latest_products': latest_products[0:20]}
return render(request, 'search/index.html', context)

和模板

{% if latest_products %}
  {% for product in latest_products %}
      <ul>
        <li id="col_one">
          <h5>{{product.avg_price.estimated_price}}</h5>
          <h5>{{product.model}}</h5>

我得到product.model但不是product.avg_price.estimated_price

0 个答案:

没有答案
相关问题