0

Currently I have this models:

class Group(models.Model):
    def __str__(self):
        return(self.name)

    dependency = models.ManyToManyField('self',related_name='group_rel')
    name = models.TextField()


class Publication(models.Model):

    name = models.TextField()
    group = models.ManyToManyField(Group, related_name='group_dependency')

I can get all fathers(groups) for one group.

group = Group.objects.filter(pk=1)[0]
group.dependency.all()

But I want to query all childrens(groups) for one group.

dir(group)

['DoesNotExist', 'MultipleObjectsReturned', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'date_error_message', 'delete', 'dependency', 'from_db', 'full_clean', 'get_deferred_fields', 'group_dependency', 'id', 'name', 'objects', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'seri alizable_value', 'unique_error_message', 'validate_unique']

Note: Publication is this question is not used. I only show it because there are a many2many to group.

guibos
  • 37
  • 1
  • 8
  • Possible duplicate of [Django ManyToMany relation to 'self' without backward relations](https://stackoverflow.com/questions/19837728/django-manytomany-relation-to-self-without-backward-relations) – binpy Nov 19 '17 at 22:26
  • Correct! Thanks you! – guibos Nov 20 '17 at 20:29

1 Answers1

1

You've named the many-to-many field dependency, so that's what you should use.

group.dependency.all()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks to reply, but this it returned all father of this group, not all childrens of this group. – guibos Nov 19 '17 at 15:58
  • It's not clear what you are treating as parent and child here. But if you want the reverse, then use the related name: `group.group_rel.all()`. – Daniel Roseman Nov 19 '17 at 16:08
  • Yep can be not clear what I am treating as parent and child, my mistake. I tried with `group.group_rel.all()` but group don't have attribute `group_rel` `AttributeError: 'Group' object has no attribute 'group_rel'` – guibos Nov 19 '17 at 16:31