简体   繁体   中英

How get related objects by field name?

I have these models:

class Category(models.Model):
        name =   models.CharField(blank=True)

class Element(models.Model):
    name =   models.CharField(blank=True)
    categories = models.ManyToManyField(Category, related_name='places', blank=False, null=True)

How to get all categories by name of field?

element._meta.get_field('category') return ManyToManyField. How to get all categories from this object

UPD: I need an access by name: I iterated by field names and collect related objects.

Example:

names = []
for field_name in ['categories', 'some_another_m2m_field_name']:
    for related_object in objects._meta.get_field(field_name).all():
        names.append(related_object.name)

thank you

我猜这会做到:

element._meta.get_field('categories').value_from_object(element)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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