Django Relational database lookups
-
13-09-2019 - |
Question
I cant figure out how to do relationships.
I have a products model and a stores model. A product has a foreign key to the stores.
So i would like to get the product name, and the store name in the same lookup.
Since the products model is:
class Products(models.Model):
PrName = models.CharField(max_length=255)
PrCompany = models.ForeignKey(Companies)
And the company model is:
class Companies(models.Model):
ComName = models.CharField(max_length=255)
How do i make django return ComName (from the companies model) when i do:
Prs = Products.objects.filter(PrName__icontains=ss)
Solution
Assuming you get results:
Prs[0].PrCompany.ComName # Company name of the first result
If you want all the company names in a list:
company_names = [product.PrCompany.ComName for product in Prs]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow