我有两个具有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]


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

最佳答案

尝试:

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

关于django - 在Django中,您如何检索多对多相关类的字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/928264/

10-12 16:33