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
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()
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^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With