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.Ma开发者_开发问答nyToManyField('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.
Service.objects.filter(plan_set__isnull=True)
should do.
You may find further explanation in the documentation.
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?
精彩评论