Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' - django

I have a staff model which can be assigned to many other groups model

I tried calling to get a response of what groups does this staff belong to but I keep on getting errors.

Can someone please give me a hand? User model

class Staff(Model):
    groups = ManyToManyField(Group,
                             related_name="%(class)ss",
                             related_query_name="%(class)s",
                             blank=True)

class Group(Model):
    creator = ForeignKey(Employer,
                         on_delete=CASCADE,
                         related_name="%(class)ss",
                         related_query_name="%(class)s")
    group_name = CharField(max_length=256, unique=True)
    created_at = DateTimeField(auto_now_add=True)

I have tried a few ways such as

staff = Staff.objects.filter(pk=1)
groups = staff.group.all()  # or 
groups = staff.group_set.all()  # or
groups = staff.group.filter()

and some other ways that I can't remember but I keep on getting errors.

Thanks in advance

like image 516
Dora Avatar asked Jan 31 '17 00:01

Dora


2 Answers

Django filter() returns a QuerySet object, which is a container of results. So, you need to pick a specific result object before trying to access the fields.

results = Staff.objects.filter(pk=1)
for staff in results:
    print staff.groups.all()
like image 60
Praveen Yalagandula Avatar answered Oct 17 '22 02:10

Praveen Yalagandula


in my case I was trying to access the models.Model class's attribute, instead of the data object that model can return. to exemplify this

django.db

class BarModel(django.db.models.Model):
    name = django.db.models.CharField(256)
    ...

class FooModel(django.db.models.Model):
    bar = django.db.models.ForeignKey('BarModel')

FooModel.bar.name  # AttributeError
# the attribute of the model doesn't exist^
# *** AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'name'

FooModel.objects.all()[0].bar.name
# the attribute I meant to reference^
like image 33
ThorSummoner Avatar answered Oct 17 '22 01:10

ThorSummoner