C132
C132

Reputation: 123

How to filter out objects that do not have a relationship with another form in Django?

I have two samples in an application built using Django:

class User(models.Model):
    email = models.EmailField()

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

I want to filter out all users who don't have any products in the store.

How do I do this?

Upvotes: 0

Views: 1078

Answers (2)

kamyarmg
kamyarmg

Reputation: 894

User's model can access Product's objects, for this situation you can filter all users that product_set is null, User.objects.filter(product__isnull=True)

Upvotes: 4

vinkomlacic
vinkomlacic

Reputation: 1879

This seems the simplest:

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

Upvotes: 1

Related Questions