2017-06-20 41 views
0

我有兩個型號:混淆Queryset.annotate()

class Property(models.Model): 
    # code here... 

class AccommodationType(models.Model): 
    property = models.ForeignKey(Property, related_name='accommodation_types') 
    # rest of code here... 

我試圖向是註釋屬性的查詢集與相關AccommodationType的數目,並通過此數量的值過濾。因此,這裏是我的代碼:

qs = Property.objects.all() 
qs.annotate(acc_types_count=Count('accommodation_types')) 
filtered = qs.filter(acc_types_count=1) 

,在這裏我得到了錯誤:

django.core.exceptions.FieldError: Cannot resolve keyword 'acc_types_count' into field. Choices are: # ...rest of the fields 

我哪裏錯了?

回答

1

annotate,就像filter一樣,不改變查詢集但是返回一個新的查詢集。你需要重新分配到qs

qs.annotate(acc_types_count=Count('accommodation_types')) 

或與原查詢結合起來:

qs = Property.objects.all().annotate(acc_types_count=Count('accommodation_types')) 
+0

謝謝,看起來像我的大腦慢慢冶煉:) – Compadre