在Django中,如何检索多对多相关类的字段?

时间:2009-05-29 21:35:44

标签: django

我有两个具有ManyToMany关系的类。我想从第一个类中选择一个并访问相关类的字段。看起来这应该很容易。例如:

class Topping(models.Model):
  name = models.CharField(max_length=40)

class Pizza(models.Model):
  name = models.CharField(max_length=40)
  toppings = models.ManyToManyField(Topping)

所以我想做类似的事情:

Pizza.objects.filter(name = 'Pizza 1')[0].toppings[0]

但这对我不起作用。谢谢你的帮助。

1 个答案:

答案 0 :(得分:26)

尝试:

Pizza.objects.filter(name = 'Pizza 1')[0].toppings.all()[0]

它对我有用(不同型号,但想法是一样的):

>>> Affiliate.objects.filter(first_name = 'Paolo')[0]
<Affiliate: Paolo Bergantino>
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients
<django.db.models.fields.related.ManyRelatedManager object at 0x015F9770>
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients[0]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'ManyRelatedManager' object is unindexable
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients.all()
[<Client: Bergantino, Amanda>]
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients.all()[0]
<Client: Bergantino, Amanda>

有关其原因的更多信息,check out the documentation