2009-05-29 10 views
14

私はManyToMany関係を持つ2つのクラスを持っています。私は最初のクラスから1つを選択し、関連するクラスのフィールドにアクセスしたいと思います。これは簡単だと思われる。たとえば: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

関連する問題