2

I have the following relationships:

class Customer(models.Model):  
    user = models.OneToOneField(User, on_delete=models.CASCADE)  

class Post(models.Model):  
    customer = models.ForeignKey('common.Customer', 
    mentions = models.ManyToManyField('common.Customer',related_name='mentions')

I want to get all of the users that are mentioned in a post. I'm thinking something like this:

customer = Customer.objects.get(user=request.user)
posts = Post.objects.filter(mentions__in=customer).order_by('-created_at')

Is this close to what I'm trying to accomplish?

Atma
  • 29,141
  • 56
  • 198
  • 299

3 Answers3

0

Try this line

users = User.objects.filter(mentions__isnull=False)
Suhaib Roomy
  • 2,501
  • 1
  • 16
  • 22
0

I saw this in the django many to many documentation and it worked:

posts = Post.objects.filter(mentions__pk=customer.id)
Atma
  • 29,141
  • 56
  • 198
  • 299
-1

It absolutely isn't, I'm afraid.

customer = Customer.objects.get(user=request.user)
posts = Post.objects.filter(mentions__in=customer).order_by('-created_at')

Would fail at mentions__in = customer because the __in lookup expects an iterable (which a single customer is not).

Aside from that, that query would give you all posts in which customer was mentioned, which could also be achieved in two more straight forward ways:

posts = Post.objects.filter(mentions=customer).order_by('-created_at')

posts = customer.mentions.order_by('-created_at') # using the 'related_name' from the customer's side

You want to get all the users that are mentioned in a post. But what post? You forgot to mention that in your question. You only gave us the current user (request.user), who can have multiple posts.
I'm going to guess and show how you could get all other users mentioned in posts made by the current user.
To make things clearer in respect to the related_name of that relation, I will change it to related_name = 'mentionend'.

posts = Post.objects.filter(mentions=customer) # all posts of the current user

# all other users mentioned in those posts
users = Customer.objects.exclude(user=customer).filter(mentionend__in=posts) # using 'related_name'
# or
users = posts.mentions.exclude(user=customer) 
CoffeeBasedLifeform
  • 2,296
  • 12
  • 27