Search code examples
pythondjangomanytomanyfield

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)

Solution

  • This was the answer:

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