Django - ReverseManyToOneDescriptor'对象没有属性' all'

时间:2016-12-30 15:11:45

标签: django

我可以看到很多与我相关的问题,当我查看它们时,我可以看到我的代码应该正常工作,但是我得到了以下错误?

模型:

class Circuits(models.Model):    
    site_data = models.ForeignKey(SiteData,verbose_name="Site")   
    order_no = models.CharField(max_length=200,verbose_name="Order No")
    expected_install_date = models.DateField()
    install_date = models.DateField(blank=True,null=True)
    circuit_type = models.CharField(max_length=100,choices=settings.CIRCUIT_CHOICES)    
    circuit_preference = models.CharField(max_length=20,verbose_name="Circuit Preference",choices=settings.CIRCUIT_PREFERENCE,blank=True,null=True)
    circuit_speed = models.IntegerField(blank=True,null=True)
    circuit_bearer = models.IntegerField(blank=True,null=True)

class CircuitMaintenance(models.Model): 
    circuit = models.ForeignKey(Circuits,verbose_name="Circuit", related_name='maintenance')
    ref = models.CharField(max_length=200,verbose_name="Ref No")
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    notes = models.TextField(blank=True,null=True)

错误

circuits = Circuits.objects.filter(site_data__id=1)
for i in Circuits.maintenance.all():
 print i
AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all'

编辑: 用小写c修改后仍然出错:

>>> from sites.models import Circuits
>>> circuits = Circuits.objects.filter(site_data__id=1)
>>> for i in circuits.maintenance.all():
...  print i
...
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'maintenance'
>>>

1 个答案:

答案 0 :(得分:6)

您需要使用变量circuits = Circuits.objects.filter(site_data__id=1) for cm in circuits: maintenances = cm.maintenance.all() for maintenance in maintenances: print(maintenance )

related_name

如果您没有定义circuits.circuitmaintenance_set.all() : ,则可以执行以下操作:

{{1}}