Reputation: 167
Check the models below
Now I want to join the tables and get product name and price
I cannot join the tables as I have no column in Product model referencing Price model
class Product(models.Model):
name = models.CharField(max_length=100)
class Price(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.IntegerField()
Upvotes: 2
Views: 118
Reputation: 476813
You can use .select_related(...)
on the Price
model, like:
prices = Price.objects.select_related('product')
Then you can for example iterate over it, and print the product name together with the price, like:
for price in prices:
print('{}: {}'.format(price.product.name, price.price))
or you can use .annotate(...)
to take fields from a related model, like:
from django.db.models import F
products = Product.objects.annotate(price=F('price__price'))
and then print it with:
for product in products:
print('{}: {}'.format(product.name, product.price))
Finally you can .prefetch_related(...)
the Price
s, and then iterate over these, like:
products = Product.objects.prefetch_related('price_set')
for product in products:
prices = product.price_set.all()
if prices:
for price in prices:
print('{}: {}'.format(product.name, price.price))
else:
print('No prices for {}'.format(product.name))
That being said, if the price does not change in time, by country, etc. then it might be better to store the price in the Product
.
Upvotes: 1