考虑到以下简化模型,我需要返回一个ManyToManyField的空ManyToManyField,但是我收到一个"AttributeError:'ReverseManyRelatedObjectsDescriptor‘对象没有属性'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如何访问泛型类方法中的"Bear"-Class或相应的“长颈鹿”-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']发布于 2016-11-25 19:14:37
错误消息明确指出了一个问题,即您要返回的对象没有名为"none“的属性。这可能就是你想要的:
if animals:
return animals.siblings.exclude(id=target_animal.id)
else
cls_obj.siblings = []
return cls_obj.siblingshttps://stackoverflow.com/questions/40810290
复制相似问题