alex
alex

Reputation: 2541

Django ManyToMany field get all values from an object without a 'for'

Is it possible to get the values of a ManyToMany from an object without using a 'for'?

models.py

class Citizenship(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Citizenship"

    def __str__(self):
        return self.name

class Anexa(models.Model):
    name = models.CharField(max_length=150, help_text="3")
    citizenship = models.ManyToManyField(Citizenship, help_text="4")

I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this:

for citizenships in x.citizenship.all():
    print(citizenships.name)

Upvotes: 2

Views: 7317

Answers (3)

alex
alex

Reputation: 2541

This was the answer:

print(', '.join(x.citizenship.values_list('name', flat=True))

Upvotes: 3

Sean Parsons
Sean Parsons

Reputation: 762

If you want to abstract away the looping you can create a method on the model:

class Anexa(models.Model):
    def print_citizens_names(self):
        for name in self.citizenship.values_list('name', flat=True):
            print(name)

Then in your codebase you can just do this:

x.print_citizens_names()

Upvotes: 1

martinB0103
martinB0103

Reputation: 245

The closest you will get is a Values List https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values-list, which you would still have to loop through to print individually.

x.citizenship.values_list('name', flat=True)

Upvotes: 7

Related Questions