Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检索ManyToManyField的类_Python_Django_Django Models_Class Method - Fatal编程技术网

Python 检索ManyToManyField的类

Python 检索ManyToManyField的类,python,django,django-models,class-method,Python,Django,Django Models,Class Method,给定以下简化模型,我需要返回ManyToManyField的空查询集,但收到 “AttributeError:'ReverseManyRelatedObjectsDescriptor'对象没有属性'none'” 错误消息清楚地指出了问题所在,即您返回的对象没有名为“none”的属性。这可能是您想要的: if animals: return animals.siblings.exclude(id=target_animal.id) else cls_obj.siblings = []

给定以下简化模型,我需要返回ManyToManyField的空查询集,但收到 “AttributeError:'ReverseManyRelatedObjectsDescriptor'对象没有属性'none'”


错误消息清楚地指出了问题所在,即您返回的对象没有名为“none”的属性。这可能是您想要的:

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

遗憾的是,这没有帮助,因为我不是在寻找cls_obj的空查询集或空列表(这将是BearFamily的空查询集),而是在ManyToMany字段中引用的类的空查询集(即空熊或长颈鹿查询集)。我知道它们的存在,因为“Bear.objects.none()”确实返回一个空查询集。Bear是另一个django类(我将把它添加到我的代码示例中以使其更加清晰)好的,如果我理解正确,那么如果查询中没有与目标动物匹配的动物,那么您试图将queryset定义为空。在这种情况下,您不需要在基类(AnimalFamily)中设置空查询集,而是将该操作移动到子类中。在这种情况下,您的基类定义将如下所示:class AnimalFamily(models.Model):#objects=GetOrNoneManager()您使用django方法名称作为类属性sides=objects.none()class AnimalFamily(models.Model):sides=GetOrNoneManager.objects.all()增加了混淆这样,以后失败的行在语法上是正确的。抱歉所有的格式问题-仍然习惯在这里发布。
# 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']
if animals:
  return animals.siblings.exclude(id=target_animal.id)
else
  cls_obj.siblings = []   
  return cls_obj.siblings