查找只有一个特定相关模型的模型
Find models that have only one particular related model
考虑以下模型:
class Product(models.Model):
name = models.CharField(max_length=...)
class Size(models.Model):
name = models.CharField(max_length=...)
products = models.ManyToManyField(Product, through=ProductXSize,
related_name='sizes', related_query_name='size')
class ProductXSize(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE,
related_name='productxsizes', related_query_name='productxsize')
size = models.ForeignKey(Size, on_delete=models.CASCADE,
related_name='productxsizes', related_query_name='productxsize')
我想要实现的是:
for p in Product.objects.filter(sizes=[Size.object.get(...)]):
...
也就是说,找到具有一种尺寸的产品,并且是特定尺寸的产品。
您需要用聚合值注释查询集:
https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#filtering-on-annotations
Product.objects.annotate(size_cnt=Count('size'))\ # annotate
.filter(size_cnt=1)\ # keep all that have only one size
.filter(size=...).all() # keep all with a certain size
考虑以下模型:
class Product(models.Model):
name = models.CharField(max_length=...)
class Size(models.Model):
name = models.CharField(max_length=...)
products = models.ManyToManyField(Product, through=ProductXSize,
related_name='sizes', related_query_name='size')
class ProductXSize(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE,
related_name='productxsizes', related_query_name='productxsize')
size = models.ForeignKey(Size, on_delete=models.CASCADE,
related_name='productxsizes', related_query_name='productxsize')
我想要实现的是:
for p in Product.objects.filter(sizes=[Size.object.get(...)]):
...
也就是说,找到具有一种尺寸的产品,并且是特定尺寸的产品。
您需要用聚合值注释查询集:
https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#filtering-on-annotations
Product.objects.annotate(size_cnt=Count('size'))\ # annotate
.filter(size_cnt=1)\ # keep all that have only one size
.filter(size=...).all() # keep all with a certain size