lmlf
lmlf

Reputation: 111

How to select all objects that aren't in a manytomany relation in Django

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.

Upvotes: 4

Views: 1208

Answers (2)

lmlf
lmlf

Reputation: 111

OK, I got this using a raw SQL query:

services = Service.objects.raw('SELECT * FROM accounts_service WHERE id NOT IN(SELECT service_id FROM accounts_plan_services);')

Anyway, can I do this without a raw SQL query?

Upvotes: 1

Michal Chruszcz
Michal Chruszcz

Reputation: 2490

Service.objects.filter(plan_set__isnull=True) should do.

You may find further explanation in the documentation.

Upvotes: 4

Related Questions