Hello, i have a problem that i cant figure out how to filter correct relations.
Here are my models:
class Company(models.Model):
customers = models.ManyToManyField("app_organisation.Customer", related_name="companies")
class CustomerTask(models.Model):
company = models.ManyToManyField(Company, related_name="tasks")
class Customer(models.Model):
tasks = models.ManyToManyField(CustomerTask, related_name="customer")
Basically the structure separates customers and tasks for each company.
In my Viewset im trying to prefetch the tables and filter out for each company customers and tasks:
def get_queryset(self):
# Here is the wrong filter. both queries do not work as expected
# task_subquery = CustomerTask.objects.filter(customer=OuterRef("id"), company__in=Subquery(Company.objects.filter(tasks=OuterRef("id")).values("id"))).values("id")
task_subquery = CustomerTask.objects.filter(customer=OuterRef("id"),
company__in=OuterRef("company__id")).values("id")
company_query = Company.objects.prefetch_related(
Prefetch("customers", queryset=Customer.objects.prefetch_related(
Prefetch("tasks", queryset=CustomerTask.objects.filter(id__in=Subquery(task_subquery)
)))))
return company_query
My Serializers have the following schema:
class CustomerTaskSerializer(serializers.ModelSerializer):
class Meta:
model = CustomerTask
fields = ["id", "name"]
class CustomerSerializer(serializers.ModelSerializer):
tasks = CustomerTaskSerializer(many=True, read_only=True)
class Meta:
model = Customer
fields = ["id", "name", "tasks"]
class CompanySerializer(serializers.ModelSerializer):
customers = CustomerSerializer(many=True, read_only=True)
class Meta:
model = Company
fields = "__all__"
read_only_fields = ["name"]
When i return company i want to input its customers and tasks which belong to the company.
In get_query i struggle to filter that correctly.
I have Company A and Company B
both have Customer C
and Company A + Customer C have Task D and Task E
but it returns for both companies Task D on Customer C