views:

113

answers:

1

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)
+7  A: 

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]
Johnny G
For a faster list, only hit the database once: `company_names = Prs.values_list('PrCompany__ComName')`