Python 如何在Django中查询未被其他模型引用的模型

Python 如何在Django中查询未被其他模型引用的模型,python,django,django-models,Python,Django,Django Models,嗨,我想知道如何在Django的ORM中进行此查询。考虑以下模型: class Person(model.Models): name = models.CharField(max_length=16) car = models.ManyToManyField("Automobile") class Automobile(model.Models): model = models.CharField(max_length=16) 我想找到所有没有被人引用的汽车。在Dja

嗨,我想知道如何在Django的ORM中进行此查询。考虑以下模型:

class Person(model.Models):
    name = models.CharField(max_length=16)
    car = models.ManyToManyField("Automobile")

class Automobile(model.Models):
    model = models.CharField(max_length=16)
我想找到所有没有被人引用的汽车。在Django如何做到这一点? 我想这样做:

am_no_person = []
for am in Automobile.objects.all():
    if not am.person_set.count():
        am_no_person.append(am)
但这看起来效率很低,而且不会返回QuerySet对象
python列表。此外,在大型数据集上,这将非常缓慢。

您可以尝试以下方法:

all_persons = Person.objects.all().values_list('car__id', flat=True)
auto_without_pers = Automobile.objects.exclude(id__in=all_persons)

因为查询集是延迟加载的,这将导致一个sql查询。

Automobile.objects.filterperson\uuuuu isnull=True?的副本@warath coder,情况不同,因为您给出的查询集本身有M2M关系,因此他可以执行一个subproducts\uuuu isnull=True,在我的例子中,我不能做一个Automobile.objects.filterperson\uuuu isnull=True,因为Automobile中没有person属性,关系来自Personokay,我的错,我认为它起作用了。LOLit应该。。。django建立关系,如果需要,可以通过在Person M2M中输入'related_name='来控制名称