如何在 Django 中选择不属于多对多关系的所有对象
我在应用程序中有以下模型(已恢复):
class Account(models.Model):
name = models.CharField(max_length=64)
plans = models.ManyToManyField('Plan')
extra_services = models.ManyToManyField('Service')
class Plan(models.Model):
name = models.CharField(max_length=64)
services = models.ManyToManyField('Service')
class Service(models.Model):
name = models.CharField(max_length=64)
这里的计划只是服务的聚合,但帐户可能有单独的服务。在管理(帐户)中我想显示一个选择框,其中包含不与任何计划绑定的所有服务(extra_services)。我可以用来获取此信息的最佳查询集是什么(在 limit_choices_to 中)?
PS:我不想迭代所有计划来获取所有链接的服务 ID,然后将它们排除在过滤器中。
I have the following models (resumed) in an application:
class Account(models.Model):
name = models.CharField(max_length=64)
plans = models.ManyToManyField('Plan')
extra_services = models.ManyToManyField('Service')
class Plan(models.Model):
name = models.CharField(max_length=64)
services = models.ManyToManyField('Service')
class Service(models.Model):
name = models.CharField(max_length=64)
Plan here is just an aggregation of services, but an account may have separate services. In admin (Account) I want to show a select box with all Services (extra_services) that AREN'T TIED with any Plan. What's the best queryset I can use to get this (in limit_choices_to)?
PS: I don't want to iterate over all Plans to get all the Services ids that are linked and after that exclude them in a filter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Service.objects.filter(plan_set__isnull=True)
应该可以。您可以在文档中找到更多说明。
Service.objects.filter(plan_set__isnull=True)
should do.You may find further explanation in the documentation.
好的,我使用原始 SQL 查询得到了这个:
无论如何,我可以在没有原始 SQL 查询的情况下执行此操作吗?
OK, I got this using a raw SQL query:
Anyway, can I do this without a raw SQL query?