How could I make this mysql query into 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
I have already tried
latest_products = Products.objects.all().prefetch_related("avg_price")
but this is translated by django as
SELECT `search_products`.`id`, `search_products`.`size`, `search_products`.`year`, , `search_products`.`model`, `search_products`.`avg_price_id`
FROM `search_products`
and
latest_products = Products.objects.all().select_related("avg_price")
This is translated by django as:
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` )
if I run the above SQL in the database I get the proper result...
Edit: Models and views
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
Template
{% 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_relatedorprefetch_relatedfor this, you want to use filter to tie to the other model, assuming a Foreign Key or Many to Many relationship. Can you post your model code?