How do you access a ForeignKey's other attribute in Django?

Viewed 58

I've been looking for a way to retrieve a model's attribute via ForeignKey(related_name). I'm going to paste the code below. Django version is 3.1, while Python version is 3.7.

accounts.models.py

class Company(models.Model):
    name = models.CharField(max_length=60)
    industry = models.CharField(max_length=20, choices = INDUSTRY_CHOICES, default="agriculture")


partner.models.py

class Partnership(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partnership_creator_set")
    partner = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="partner_set")

So when a Company partners with another Company, 2 instances of Partnerships are created. First instance will have the first company as the creator, while Second instance will have the first company as the partner. How do i get get the number of existing partners for a specific company? I'm able to get a Company instance then use the related name to get the existing partnerships. If I try something like Company.partnership_creator_set.all(), I'm able to get the list of partnerships. What I want is to look for the current partners which is in the "partner" attribute in the Partnership model.

2 Answers

If this solves your problem:

Let's say you want to get partners for a Company object with id=5

companyObj = Company.objects.get(id=5)
partners = Partnership.objects.filter(creator=companyObj).values_list('partner',flat=True)

partners will be the queryset of all the partners of Company with id=5

Ref: In case you need to dig down values_list

You could count the number of partners of a company directly with this line of code

Company.objects.filter(partner_set__creator__id=<your_company_id>).distinct().count()

For more information, please see the Django documentation of relate field lookups

Related