django 过滤 manytomany 或无记录

django filter by manytomany or no record

我有模型

class Product(models.Model):
    title = models.CharField(...)

class PropertyType(models.Model):
    title = models.CharField(...)

class Property(models.Model):
    property_type = models.ForeignKey(PropertyType)
    product = models.ForeignKey(Product, related_name='properties')
    value = models.CharField(...)

那么,我如何过滤具有某些值和 property_type 的属性的产品,并包括没有 属性 且具有相同 property_type

的产品

像这样

properties = Property.objects.filter(property_type__pk=12, value='anyValue')
products = Product.objects.filter(Q(properties__in=properties)|
              Q(NO PROPERTY RECORD WITH PROPERTYTYPE__ID=12 FOR PRODUCT))

正确的做法是properties = Property.objects.filter(property_type__pk__contains=12, value='anyValue')第二个没看懂

凭经验找到答案

properties = Property.objects.filter(property_type__pk=12, value='anyValue')
products = Product.objects.filter(Q(properties__in=properties)|
          ~Q(properties__property_type__pk__in=[12]))