Elsa
Elsa

Reputation: 626

How to get queryset of manytomanyfiled through foreignkey(model only has 2 field)

how to queryset manytomanyfiled through a foreignkey, my model only has 2 field as below:

class Model_A(models.Model):
    user_b = models.ForeignKey(User_B, on_delete=models.CASCADE, null=True)
    project_c = models.ManyToManyField(Project_C, related_name="+", blank=True)

user_b has many project_c as below, I want to get the queryset of the list of project_c of current user_b:

id project_c_id
1   1
2   2    
3   3
4   4 
..  ..
..  .. 

Thanks so much, really appreciate for any advice!!!

Upvotes: 0

Views: 63

Answers (4)

user9774106
user9774106

Reputation:

You need to related_name between Model_A and Project_C as below:

class Model_A(models.Model):
    user_b = models.ForeignKey(User_B, on_delete=models.CASCADE, null=True)
    project_c = models.ManyToManyField(Project_C, related_name="projects", blank=True)

Then query it by below code:

Project_C.objects.filter(permits__user=self.request.user)

Upvotes: 1

Alberto
Alberto

Reputation: 1408

You can return the Model_A objects filtered by user an return only their project_c values.

Model_A.objects.filter(user_b__id=user_id).values_list('project_c')

Upvotes: 2

Ivan Lavrenov
Ivan Lavrenov

Reputation: 76

model = Model_A.objects.get(user_b=user)
projects = Project_c.objects.filter(model_a_set__contains=model)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476739

If I understand it correctly, you want to obtain a queryset that contains Project_C instances for which the user of a corresponding Model_A is a specific user.

We can query this with:

Project_C.objects.filter(model_a__user=someuser)

Upvotes: 1

Related Questions