【问题标题】:How to query for Model in Django that is not referenced by another Model如何在 Django 中查询未被另一个模型引用的模型
【发布时间】:2015-02-26 05:15:23
【问题描述】:

您好,我想知道如何在 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)

我想找到所有未被 Person 引用的 Automobile。在 Django 中如何做到这一点? 我想过这样做:

am_no_person = []
for am in Automobile.objects.all():
    if not am.person_set.count():
        am_no_person.append(am)

但这看起来效率太低,而且不会返回 QuerySet 对象 一个python列表。这在大型数据集上也会非常慢。

【问题讨论】:

  • Automobile.objects.filter(person__isnull=True) ?
  • @warath-coder,情况不同,因为你给的那个和自己有M2M关系,所以他可以做一个subproducts__isnull=True,在我的情况下我不能做一个Automobile.objects.filter(person__isnull=True),因为有汽车中没有人属性,关系来自人
  • 好吧,我的错,我认为它有效。哈哈
  • 它应该... django 建立关系,如果需要,您可以通过在 Person M2M 中放置 'related_name=' 来控制名称

标签: python django django-models


【解决方案1】:

你可以试试这样的:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多