Le Duy Khanh
Le Duy Khanh

Reputation: 1369

Django query with ManyToMany relationship through

I am implementing the connect function like Linkedin. My models are

class AFSUser(models.Model):
    connects = models.ManyToManyField("self", through='UserConnect', symmetrical=False)

class UserConnect(models.Model):
    date_followed = models.DateTimeField(auto_now_add=True)
    date_approved = models.DateTimeField(null=True, blank=True)
    date_rejected = models.DateTimeField(null=True, blank=True)
    requester = models.ForeignKey(AFSUser, on_delete=models.CASCADE, related_name='request_user')
    acceptor = models.ForeignKey(AFSUser, on_delete=models.CASCADE, related_name='accept_user')

I want to list connections of a user. I tried

approved_connections = UserConnect.objects.filter(Q(requester=afsUser) | Q(acceptor=afsUser),                                                  date_aprroved__isnull=False,
                                                                  date_rejected__isnull=False)

Then get the list from there. Any other way so i can do

users = userA.connects.filter(...)

Upvotes: 0

Views: 82

Answers (1)

Nader Alexan
Nader Alexan

Reputation: 2222

Yes, you can use through

userA.connects.through.objects.filter(Q(requester= userA)|Q(acceptor=userA))

Upvotes: 2

Related Questions