2009-05-29 82 views
14

我有兩個具有ManyToMany關係的類。我想從第一堂課中選擇一個,並訪問相關課程的各個字段。這似乎應該很容易。例如:在Django中,如何檢索多對多相關類的字段?

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] 

但是,這並不爲我工作。謝謝你的幫助。

回答

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

+0

太好了。謝謝。 – Mitch 2009-05-29 21:52:07

相關問題