Querying model by ForeignKey to receive data in another ForeignKey?

Viewed 19

I am having trouble running a query through a table that I built as basically a linkage type table to link Company and Package

class CompanyPackageLink(models.Model):
    company = models.ForeignKey('business.Company', related_name='company_packages')
    package = models.ForeignKey('business.Package', related_name='packages')

I am trying to query the CompanyPackage table by company and then retrieve all packages associates to that query.

I have something like...

company = Company.objects.get(employee=self.request.user)
company_packages = CompanyPackageLink.objects.filter(company=company).select_related('package')

Now this returns a correct quesyset, but it returns the CompanyPackage instance.

<QuerySet [<CompanyPackageLink: companyA: PackageA>, <CompanyPackageLink: CompanyB: PackageB>]>

I would like my query to return the actual Package model instance where I can retrieve name, price, etc.

So I would like the returned queryset to actually return this..

<QuerySet [<Package: $100.00>, <Package: $200.00>]>

Any help is appreciated!

1 Answers

You can easily query with:

Package.objects.filter(packages__company=company)

it is possible that there are two (or more) CompanyPackageLink with the same Package and Company. In that case the QuerySet will contain that Package multiple times. You can avoid that by using .distinct() [Django-doc]:

Package.objects.filter(packages__company=company).distinct()
Related