HBMCS
HBMCS

Reputation: 776

Accessing a property coming from manytomany field

This is my models.py:

class Role(models.Model):
    type= models.CharField(max_length=30)

class Profile(models.Model):
    role = models.ManyToManyField(Role, blank=True)

    def is_composer(self):
        return self.role['Composer']

This is my view.py:

from .models import Profile, Role
def profiles_filtered(request, type):
    model = Profile
    if type == 'composers':
        queryset = Profile.objects.filter(is_composer = True)

My urls.py:

urlpatterns = [
    path('profiles/<str:type>/', views.profiles_filtered, name="profiles"),
]

And my template:

<li><a href="{% url 'profiles' 'composers' %}"> Composers</a></li>

When I click on the link, I get to /profiles/composers/, which should list all the profiles containing the role 'Composer'. I get a

FieldError at /profiles/composers/
Cannot resolve keyword 'is_composer' into field.

The Role type contains many roles, one of which is 'Composer'. How can I list only the profiles which contain a 'Composer' role?

addendum

If I use

    if type == 'composers':
        queryset = Profile.objects.filter(role == 'Composer')

I get

NameError at /profiles/composers/
name 'role' is not defined

Upvotes: 0

Views: 24

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

If you are asking for the filter where role is equals Composer then:

if type == 'composers':
    queryset = Profile.objects.filter(role__type__contains="Composer")

type is property of role object so, role__type is equivalent to role's type and __contains is django filter process, lets say.

Upvotes: 1

Related Questions