鉴于以下简化模型,我需要返回一个ManyToManyField的空QuerySet,但我收到一个 " AttributeError:' ReverseManyRelatedObjectsDescriptor' object没有属性' none'"
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
如何在泛型类方法中访问&#34; Bear&#34; -Class或相应的&#34; Giraffe&#34; -Class以返回正确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']
答案 0 :(得分:2)
错误消息明确指出问题,即您要返回的对象没有名为&#34; none&#34;的属性。这可能是你想要的:
if animals:
return animals.siblings.exclude(id=target_animal.id)
else
cls_obj.siblings = []
return cls_obj.siblings