对于这些模型:
class Product(models.Model):
code = models.IntegerField()
class Failure1(models.Model):
FAILURE_CHOICES = (
('SC', 'Screen'),
('BA', 'Battery'),
('BX', 'Box'),
# etc, with 10+ choices
)
name = models.CharField(max_length=2, choices=FAILURE_CHOICES)
class Failure2(models.Model):
FAILURE_CHOICES = (
('SZ', 'Blah'),
('BB', 'Basdasd'),
('BD', 'etc'),
# etc, with 10+ choices
)
name = models.CharField(max_length=2, choices=FAILURE_CHOICES)
class Market(models.Model):
MARKET_CHOICES = (
('ED', 'Education'),
('CO', 'Commercial'),
# etc, with 10 choices
)
product = models.ForeignKey(Product)
market = models.CharField(max_length=2,choices=MARKET_CHOICES)
failure1 = models.ManyToManyField(Failure1, blank=True)
failure2 = models.ManyToManyField(Failure2, blank=True)
class Failure_MarketManager(models.Manager):
def get_queryset(self):
return super(Failure_MarketManager, self).get_queryset().filter(Q(failure2__name__isnull=False) | Q(failure1__name__isnull=False))
class Failure_Market(Market):
class Meta:
proxy = True
objects = Failure_MarketManager()
我之后的是一个管理员更改列表,它只显示那些有任何失败的市场(来自Failure1或Failure2列表)。
使用上面的代理模型,如果有多个失败,我会得到一个' get()返回多个对象'错误。
如果我将其更改为get_queryset().exclude(Q(failure2__name__isnull=True) | Q(failure1__name__isnull=True))
,我会得到零结果 - 为什么会这样?
如果我将其更改为get_queryset().filter(~Q(failure2__name__isnull=False) | ~Q(failure1__name__isnull=False))
它有效 - 为什么这会有效,但过滤器Q不会?