Django ForeignKey

时间:2019-03-10 17:02:01

标签: django relationship

我正在努力通过外壳进行反向搜索以查找外键

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

如果我输入外壳:

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

另一方面:

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

始终收到错误“投资者未将'....'归因于-> 我如何搜索反向关系?谢谢!!

1 个答案:

答案 0 :(得分:1)

外键是一对多关系,而不是一对一关系。在这里,一个投资有一个投资者,但是一个投资者有许多投资。因此,对于您的投资者,您需要使用反向关系,该关系默认为set,并且是经理:

b.investment_set.all()