I am trying to filter related_name
field with a query if it's possible. I serialize the tables.
class ProjectsSerializers(serializers.ModelSerializer):
class Meta:
model = Projects
fields = ["id", "project_id", "project_name", "tasks"]
depth = 1
Above in the fields list. tasks
is the related_table
so in the tasks table I have task_created_at
field and when I retrieve the projects table. I want to filter it by that field.
def get_projects(request):
projects = Projects.objects.filter(task_created_at__startswith="2020-04")
serializer = ProjectsSerializers(projects, many=True)
return Response(serializer.data)
Of course this: task_created_at__startswith="2020-04"
isn't working. Because task_created_at
is not in the projects. it's in the related_name
which is tasks
. So is there a way to filter tasks with getting projects
and the relevent models:
class Projects(models.Model):
project_id = models.CharField(max_length=255)
project_name = models.CharField(max_length=255)
def __str__(self):
return self.project_name
class Meta:
db_table = "projects"
class Tasks(models.Model):
projects = models.ForeignKey(Projects, on_delete=models.CASCADE, related_name='tasks', blank=True, null=True)
task_price = models.IntegerField(blank=True, null=True)
task_total_price = models.IntegerField(blank=True, null=True)
task_created_at = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.ad_kind
class Meta:
db_table = "tasks"
the example data:
[
{
"id": 6,
"order_id": null,
"project_id": "23123",
"project_name": "プレサンス グラン 茨木駅前",
"company_name": null,
"analytics_id": null,
"advertisements": [],
"tasks": [
{
"id": 1,
"task_total_price": null,
"task_created_at": "2020-04-02",
"task_due_date": "2020-04-07",
"task_modified_at": "2020-04-07T06:42:41.447Z",
"projects": 6
},
{
"id": 2,
"task_total_price": null,
"task_created_at": "2020-02-02",
"task_due_date": "2020-03-07",
"task_modified_at": "2020-04-07T06:42:41.447Z",
"projects": 6
},
]
}
]