Reputation: 626
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
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
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
Reputation: 76
model = Model_A.objects.get(user_b=user)
projects = Project_c.objects.filter(model_a_set__contains=model)
Upvotes: 1
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