1

I'm struggling to do a reverse search via the shell for a foreign key

models.py:

class Investor(models.Model):
 first_name = models.CharField(max_length = 100)
 last_name = models.CharField(max_length = 100)

 def __str__ (self):
    return '%s %s' % (self.first_name, self.last_name)

class Investment(models.Model):
 investor = models.ForeignKey(Investor, on_delete=models.CASCADE)
 feeder = models.ForeignKey(Fund, on_delete=models.CASCADE)   
 amount = models.DecimalField(max_digits=20, decimal_places=2, default="1")

 def __str__ (self):
    return self.investor

class Fund(models.Model):
 feeder = models.CharField(max_length=100)

 def __str__ (self):
    return  self.feeder

If I enter the shell:

a = Investment.objects.get(pk=1)
a.investor.first_name -> this works 

On the other hand :

b = Investor.objects.get(pk=1)
b.investment doesn't work... 
b.investor doesn't work
b.investment.feeder neither.. 

Always got the error 'Investor has not attributed '....' -> How can i search through the reverse relationships? Thanks !!

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
TMD
  • 191
  • 1
  • 2
  • 14

1 Answers1

2

A foreign key is a one-to-many relationship, not one-to-one. Here an Investment has one Investor, but an Investor has many Investments. So from your Investor you need to use the reverse relation, which be default ends in set, and is a Manager:

b.investment_set.all()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Hi Daniel. Many thanks ! Indeed. Any idea how I can use this in a html template. I'm facing there the same problem: investment.investor.first_name works. But, investor.investment.feeder doesn't... Thanks ! – TMD Mar 10 '19 at 17:19
  • But why would you think that would work? I've told you, you need to use investment_set, and it's a manager that returns a queryset which you need to iterate through because there are *many* Investments. – Daniel Roseman Mar 10 '19 at 17:28
  • Thing is that I've got a filter set. And when I include a for-loop to iterate over the investment_set, the investors without any investment disappear from the Queryset... Maybe I should create a separate topic for this one – TMD Mar 10 '19 at 17:31
  • Yes that sounds best – Daniel Roseman Mar 10 '19 at 17:31