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.
question from:
https://stackoverflow.com/questions/65840810/how-do-you-access-a-foreignkeys-other-attribute-in-django 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…