简体   繁体   English

Django ManyToMany字段从没有“ for”的对象获取所有值

[英]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'? 是否可以在不使用“ for”的情况下从对象获取ManyToMany的值?

models.py 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. 我有一个名为Alex的Anexa对象,并且有4个该对象的公民身份。 I'm searching for something equivalent to this: 我正在寻找与此等效的东西:

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

您将得到的最接近的是一个值列表https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values-list ,您仍然必须循环遍历以单独打印。

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

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()

这是答案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM