0

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?

C132
  • 103
  • 1
  • 6

2 Answers2

3

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)

kamyarmg
  • 760
  • 2
  • 6
  • 23
  • 1
    I think this would result in an error. `product_set` is not a field defined on the User model. – vinkomlacic Mar 06 '22 at 17:49
  • 1
    when you create foreignkey, Django gets a new API on the other side (reverse relation) by default _set name. in this question, user's object has a product_set that contains all user's products. you can read this question: https://stackoverflow.com/q/17328910/8157102 for more information – kamyarmg Mar 06 '22 at 18:47
  • 2
    Yes, while that is true, the reverse relation cannot be used in a filter query. – vinkomlacic Mar 06 '22 at 18:49
  • I have just checked this myself. Like I said above, the reverse relation cannot be used like this. However, you could do something like: `User.objects.filter(product__user__isnull=True)` – vinkomlacic Mar 06 '22 at 18:54
  • 2
    Tnx for your feedback, I edit the answer, we can use ```User.objects.filter(product__isnull=True)``` I test that is OK. if you want, test it and say the result – kamyarmg Mar 06 '22 at 19:04
1

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)
vinkomlacic
  • 1,822
  • 1
  • 9
  • 19
  • Can you explain that? – C132 Mar 05 '22 at 13:01
  • First you take all user ids that have a product, then you use those in an exclude query (kind of filter but in reverse) - you take all Users, but exclude those that have a product. – vinkomlacic Mar 05 '22 at 18:18