如何將這個mysql查詢導入到django ORM中?Django具有多個連接字段的ORM查詢
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
我已經嘗試
latest_products = Products.objects.all().prefetch_related("avg_price")
,但是這是由Django的翻譯爲
SELECT `search_products`.`id`, `search_products`.`size`, `search_products`.`year`, , `search_products`.`model`, `search_products`.`avg_price_id`
FROM `search_products`
和
latest_products = Products.objects.all().select_related("avg_price")
這是由Django的翻譯爲:
SELECT `search_products`.`id`, `search_products`.`size`, `search_products`.`year`, , `search_products`.`model`, `search_products`.`avg_price_id`, `search_avg_price`.`id`, `search_avg_price`.`model`, `search_avg_price`.`size`, `search_avg_price`.`year`, `search_avg_price`.`estimated_price`
FROM `search_products`
INNER JOIN `search_avg_price` ON (`search_products`.`avg_price_id` = `search_avg_price`.`id`)
,如果我在數據庫中運行我得到正確的結果上面的SQL ...
編輯:模型和視圖
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
模板
{% if latest_products %}
{% for product in latest_products %}
<ul>
<li id="col_one">
<h5>{{product.avg_price.estimated_price}}</h5>
<h5>{{product.model}}</h5>
你不爲此需要'select_related'或'prefetch_related',假設使用外鍵或多對多關係,您希望使用過濾器與另一個模型綁定。你能發佈你的模型代碼嗎? – Tom