2016-11-25 38 views
1

考慮下面的簡化模型的類,我需要返回ManyToManyField的空查詢集,但我收到 「AttributeError的:‘ReverseManyRelatedObjectsDescriptor’對象有沒有屬性‘無’」檢索ManyToManyField

class AnimalFamily(models.Model): 
    objects = GetOrNoneManager() 
    siblings = objects.none() 


class Countable(models.Model): 
    @classmethod 
    def get_peers(cls_obj,target_animal): 
    animals = cls_obj.objects.get_or_none(siblings=target_animal) 
    if animals: 
     return animals.siblings.exclude(id=target_animal.id) 
    else 
     return cls_obj.siblings.none() # <--- this fails <---- 

    class Meta: 
    abstract = True 


class BearFamily(AnimalFamily,Countable): 
    siblings = models.ManyToManyField(Bear) 

class GiraffeFamily(AnimalFamily,Countable): 
    siblings = models.ManyToManyField(Giraffe) 


class Bear(models.Model): 
    pass 

class Giraffe(models.Model): 
    pass 

如何才能訪問「Bear」類或相應的「長頸鹿」類泛型類方法返回一個空查詢正確的QuerySet?

額外的信息:

# dir(cls_obj.siblings) returns: 
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'field', 'related_manager_cls', 'through'] 

回答

2

錯誤消息明確指出的問題說你正在返回的對象沒有命名爲「無」屬性。這可能是你想要什麼:

if animals: 
    return animals.siblings.exclude(id=target_animal.id) 
else 
    cls_obj.siblings = [] 
    return cls_obj.siblings 
+0

可悲的是這並沒有幫助,因爲我不是在尋找一個空的查詢集或cls_obj的空列表(這將是BearFamily的空queryset的),而是一個空查詢集在ManyToMany字段中引用的類(即空熊或長頸鹿queryset)。我知道這些存在,因爲'Bear.objects.none()'返回一個空的查詢集。 Bear是另一個django類(我將它添加到我的代碼示例中以使其更清晰) – gimili

+0

好的,如果我正確理解這一點,那麼您試圖將查詢集定義爲空,如果查詢中沒有動物匹配目標動物。在這種情況下,您不需要在基類(AnimalFamily)中設置一個空查詢集,但將該操作移入子級。在這種情況下,您的基類定義如下所示:class AnimalFamily(models.Model): #objects = GetOrNoneManager()通過使用django方法名稱作爲類屬性添加到混淆中 siblings = objects.none( ) – postoronnim

+0

這是基類的代碼: – postoronnim