N
N
NyxDeveloper2022-03-14 22:38:11
Django
NyxDeveloper, 2022-03-14 22:38:11

Django annotate Concat() fields of related objects?

You need to display a new variable in a separate field, which is a string from the connected text fields of objects from the table linked by M2M.
Roughly speaking, there are models:

class Post(models.Model):
    name = models.CharField(max_lenght=100)

class Tag(models.Model):
    name = models.CharField(max_lenght=100)

and in the list of Post models, you need to annotate the tags field, as a single line, consisting of the names of all tags.
Can this be done using django? There is only one example in the docs:
# https://docs.djangoproject.com/en/1.8/ref/models/database-functions/#concat
# Get the display name as "name (goes_by)"
from django.db.models import CharField, Value as V
from django.db.models.functions import Concat
Author.objects.create(name='Margaret Smith', goes_by='Maggie')
author = Author.objects.annotate(
screen_name=Concat('name', V(' ('), 'goes_by', V(')'),
output_field=CharField())).get()
print(author.screen_name)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question