fischer
fischer

Reputation: 101

Get data related to manytomany field

I have two model, first one is Industries, second one is experts. My models looks like this.

class Industries(models.Model):
    name = models.CharField(max_length=255, verbose_name="Industry name")
    slug = models.SlugField(unique=True, blank=True, max_length=150)

class Expert(models.Model):
    name = models.CharField(max_length=255, blank=True, verbose_name="Expert Name")
    industry = models.ManyToManyField(Industries, blank=True, verbose_name="Industries")

on the all experts page I made an industries field clickable, when user clicked any industry, My goal is show the experts which is in this industry.

My urls.py looks like this: path('e/country/<slug:slug>', ExpertCountryView.as_view(), name="expert_country")

Now I am confused with my views.py how can I create my view (ExpertCountryView) to shows me experts with this industry. example: www.mysite.com/p/country/trade

trade is my industry. I hope all is understandable.

Upvotes: 1

Views: 34

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can filter your Experts, like:

from app.models import Expert
from django.views.generic.list import ListView

class ExpertCountryView(ListView):
    model = Expert

    def get_queryset(self):
        return super().get_queryset().filter(
            industry__slug=self.kwargs['slug']
        )

Upvotes: 1

Related Questions