2

I have to models with one to many relation with which I try to distinguish the type of my records. Let's say First model is dedicated to Book information and second model is some types such as A, B , C and there is an indirect relation from the Type table to Book, so each book could be A, B or C or any possible combination of Types. I want to use concatenation (or any other possible function in annotation to gather all the types in a field).

Book.objects.all(
).annotate(
    Types = F('TableRelation__Type__Name')
).annotate(
    CombinedTypes = Concat('Types')
)

which throws an error since only one argument is passed to be Concatenated. The result I am looking for is a CombinedTypes field filled with "ABAB" for any unique id of Book which shows that that record is an "AB" (or any other combination of A,B and C).

How can I achieve this?

Azee
  • 329
  • 6
  • 20
  • 1
    Have you read some documents like [Creating your own Aggregate Functions](https://docs.djangoproject.com/en/2.0/ref/models/expressions/#creating-your-own-aggregate-functions) and/or [http://harkablog.com/inside-the-django-orm-aggregates.html](http://harkablog.com/inside-the-django-orm-aggregates.html) and/or [https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django](https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django) ? You may override something like the Concat function to reach your goal. – Happy Ahmad Jan 04 '18 at 07:33
  • Thanks for the hints @Ahmad. I'll check the links and let you know the result. – Azee Jan 04 '18 at 07:55

1 Answers1

3

I ended up using the solution explained in this Stack-overflow answer in the post introduced by @Ahmad in comments.

Azee
  • 329
  • 6
  • 20