2016-12-30 59 views
3

我可以看到很多相關的問題和我檢查出來,從我可以看到我的代碼應該工作,但即時獲取下面的錯誤嗎?Django - ReverseManyToOneDescriptor'對象沒有任何屬性'all'

型號:

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' 

編輯:修正與小寫 仍然Ç收到錯誤:

>>> 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' 
>>> 

回答

4

您需要使用您的變量circuits

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() : 
+0

啊,是的!我把資本C! – AlexW

+0

我現在得到另一個錯誤... – AlexW

+0

我編輯了我的代碼。你需要在queryset上循環。像這樣你有Circuits對象。 – Wilfried

相關問題