Django 查询集过滤器(可能需要子查询)

发布于 2024-09-13 12:34:39 字数 555 浏览 5 评论 0原文

我想生成一个查询集来查找不匹配项。作为一个例子,

class Vehicle(models.Model):
    car = models.CharField(max_length=100)
    model= models.CharField(max_length=100)
    passengers = models.IntegerField()

我想生成一个查询,在其中我可以找到错误地列出两种不同型号的汽车。

沿着查询的思路查找如果 car = Wrangler, model = Jeep 则查找 car = Wrangler, model 不是 Jeep 的实例。

这可以在 ORM 中完成吗?还是需要使用原始 SQL? #django 中有人建议使用子查询,但我不熟悉如何执行此

示例输出 只是不匹配车辆的查询集(例如,一个对象存在 car = Wrangler, model = Ford,但另一个对象存在 car = Wrangler, model = Jeep)。我在想没有输入只是能够找到不匹配的地方。这还有道理吗?

I want to generate a queryset to find mismatches. As an example

class Vehicle(models.Model):
    car = models.CharField(max_length=100)
    model= models.CharField(max_length=100)
    passengers = models.IntegerField()

i want to generate a query where i can find cars erroneously listed with two different models.

something along the lines of a query to find that if a car = Wrangler, model = Jeep to find instances of car = Wrangler, model is not Jeep.

Is this possible to do within the ORM, or do i need to use raw SQL? Someone in #django suggested a subquery, but I am not familiar with how to do this

Sample Output
would just be a queryset of mis-matched vehicles (for example car = Wrangler, model = Ford exists for one object but car = Wrangler, model = Jeep for another object). I was thinking of not having an input just being able to find mismatches. Does this make sense yet?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黯然#的苍凉 2024-09-20 12:34:39

如果我理解您需要模型+汽车在一起是唯一的,那么您需要首先找到重复的记录:

from django.db.models.aggregates import Count

repetitve_cars_list = Vehicle.objects.values('car').annotate(count_car=Count('car')).filter(co
unt_car__gt=1)

这将为您提供使用多个模型定义的汽车

If I understand you need to model+car be unique together, so you need to find repetitive records first:

from django.db.models.aggregates import Count

repetitve_cars_list = Vehicle.objects.values('car').annotate(count_car=Count('car')).filter(co
unt_car__gt=1)

This will give you the cars that was defined with more than one model

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文