I have two models. one is Author and the other is Book. an author can have multiple books. so the id of the author is the foreign key. and I have the following data.
Author Table
id | Author Name |
---|---|
1 | Tom |
Books Table
id | Author | Book Name |
---|---|---|
1 | 1 | rescue a person |
2 | 1 | be a doctor |
I want to create a function to get the following result when I query the author record.
id | author name | books name |
---|---|---|
1 | Tom | rescue a person, be a doctor |
CodePudding user response:
for one2many and M2M, prefetch_related
is used:
from django.db.models import Prefetch
author = Author.objects.filter(pk=1).prefetch_related(Prefetch('book_set',to_attr='books'))
now, the author[0].books
gives the books of the author. ref
CodePudding user response:
If you want to avoid subsequent queries when iterating over your queryset, @Amin Mir answer is sufficient.
If you need data to be aggregated inside of your queryset, you should take a look at:
ArrayAgg for Postgres: https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/aggregates/#arrayagg
GroupConcat for MySQL and MariaDB:
https://django-mysql.readthedocs.io/en/latest/aggregates.html#django_mysql.models.GroupConcat
The GroupConcat doc example should help you with the syntax