Reputation: 191
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 !!
Upvotes: 1
Views: 43
Reputation: 599480
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()
Upvotes: 2