0

Can I join Django ORM Model properties/attributes into a string without introducing loops?

I have a django model:

class Foo(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=1000, db_collation='Latin1_General_CI_AS')

I want to select the names into a string from a result of filtering:

foos = Foo.objects.filter(id=[1,2,3])

Something equivalent of this piece of C#:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public class Foo
    {
        public string Name { get; set; }
    }

    public static void Main()
    {
        List<Foo> foos = new List<Foo>();
        foos.Add(new Foo { Name = "A1" });
        foos.Add(new Foo { Name = "A2" });
        
        Console.WriteLine(string.Join(",", foos.Select(x => x.Name)));
    }
}

Which outputs A1,A2.

Andez
  • 5,588
  • 20
  • 75
  • 116
  • 1
    `",".join(foos.values_list("name", flat=True))`? – Abdul Aziz Barkat Oct 26 '22 at 08:42
  • Does this answer your question? [How to concatenate (join) items in a list to a single string](https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string) along with [Django - how do I select a particular column from a model?](https://stackoverflow.com/questions/10704926/django-how-do-i-select-a-particular-column-from-a-model) – Abdul Aziz Barkat Oct 26 '22 at 08:45

0 Answers0