我有两个具有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)
Run Code Online (Sandbox Code Playgroud)
所以我想做一些像:
Pizza.objects.filter(name = 'Pizza 1')[0].toppings[0]
Run Code Online (Sandbox Code Playgroud)
但这对我不起作用.谢谢你的帮助.
Pao*_*ino 26
尝试:
Pizza.objects.filter(name = 'Pizza 1')[0].toppings.all()[0]
Run Code Online (Sandbox Code Playgroud)
它对我有用(不同型号,但想法是一样的):
>>> 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>
Run Code Online (Sandbox Code Playgroud)
有关其工作原理的更多信息,请查看文档.
| 归档时间: |
|
| 查看次数: |
12499 次 |
| 最近记录: |