[英]How to query all model objects except the ones that already are in another model?
I am working on a Django application.我正在开发 Django 应用程序。 I have 2 models relevant to the question:我有 2 个与该问题相关的模型:
class Quiz(models.Model):
"""
Represents a Quiz for a `Module`.
It will have a `name`
"""
name = models.CharField(max_length=200)
user = models.ManyToManyField('cme.Bussines', related_name='quizes', through='UserQuiz', through_fields=('quiz', 'user'))
def __str__(self) -> str:
return f'{self.name}'
class Trio(models.Model):
"""
Represents the content for a Module.
Each `Trio` will have, as it's name says, 3 content fields, plus the
`Module` it belongs to.
It will have a `file`, a `video` (which will be a URL to a YT video), and a `quiz`
(which will be key to `Quiz`)
"""
file = models.FileField(upload_to='legacy/classes/', max_length=254)
quiz = models.ForeignKey(Quiz, on_delete=models.SET_NULL, related_name='trios', null=True, blank=True)
video = models.URLField()
module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='trios')
user = models.ManyToManyField('cme.Bussines', related_name='trios', through='UserTrio', through_fields=('trio', 'user'))
def __str__(self) -> str:
return f'Trio {self.id} de {self.module}'
I want to query all the Quiz
zes that are not in quiz
field of Trio
.我想查询所有不在Trio
Quiz
字段中的quiz
。 Is there a way of doing this?有没有办法做到这一点?
Yes, you can query with:是的,您可以通过以下方式查询:
Quiz.objects.filter(trios=None)
This will make a LEFT OUTER JOIN and only retain Quiz
zes for which there is no related Trio
object.这将进行 LEFT OUTER JOIN 并仅保留没有相关Trio
object 的Quiz
。
You can query all Quiz
objects whose id
is seen in any Trio
object:您可以查询在任何Trio
object 中看到其id
的所有Quiz
对象:
Quiz.objects.exclude(id__in=Trio.objects.values("quiz_id"))
You can also refine the query further.您还可以进一步细化查询。 For example, let's say you want all Quiz
objects not referred by a specific subset of Trio
objects, you can do so by adding a filter in your exclude expression, something like:例如,假设您希望所有Quiz
对象不被Trio
对象的特定子集引用,您可以通过在排除表达式中添加过滤器来实现,例如:
Quiz.objects.exclude(id__in=Trio.objects.filter(...).values("quiz_id"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.