Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...