如何过滤掉Django中与其他表单没有关系的对象



我在使用Django构建的应用程序中有两个示例:

class User(models.Model):
email = models.EmailField()
class Product(models.Model):
user = models.ForeignKey(User)

我想过滤掉商店里没有任何产品的所有用户。

我该怎么做?

用户模型可以访问Product的对象,在这种情况下,您可以过滤Product_set为null的所有用户,User.objects.filter(product__isnull=True)

这似乎是最简单的:

user_ids_with_product = [product.user_id for product 
in Product.objects.all()]
Users.objects.exclude(id__in=user_ids_with_product)

最新更新