Home > Software design >  ManyToMany Model query
ManyToMany Model query

Time:12-09

I have 2 models Project and Investor Project model has a field called project_investors with a ManyToMany to the Investor model.

Models

class Investor(models.Model):

    investor_name = models.CharField(max_length=50, blank=False, unique=True)
    investor_website = models.URLField(max_length=100, blank=True)
    investor_portfolio_website = models.URLField(max_length=100, blank=True)
    investor_description = models.TextField(blank=True)
    investor_investments = models.TextField(blank=True)
    

    def __str__(self):
        return str(self.investor_name)

class Project(models.Model):

    project_name = models.CharField(max_length=50, blank=False, unique=True)
    project_website = models.URLField(max_length=50, blank=True)
    project_description = models.TextField(blank=True)
    project_investors = models.ManyToManyField(Investor, blank=True)

    def __str__(self):
        return str(self.project_name)

I then have a page the shows the Investor details and im trying to show which projects have been linked to this investor.

myview.py

@login_required
def show_investor_details(request,investor_id):
    investor = Investor.objects.get(pk=investor_id)
    form = InvestorForm(request.POST or None, instance=investor)
    project = Project.objects.all()
    project_list = get_object_or_404(Project, project_investors=investor_id)
    return render(request, 'pages/investor_details.html', {"investor": investor, "form": form,"project": project,'project_list':project_list})

Im not sure what is the correct query to pass in here project_list = get_object_or_404(Project, project_investors=investor_id)

as this error is thrown: 'Project' object is not iterable

Or maybe I have the model structure incorrect?

CodePudding user response:

a similiar question was asked and answered here https://stackoverflow.com/a/70272979/13443114

but to be explicit...use

@login_required
def show_investor_details(request,investor_id):
    investor = Investor.objects.get(pk=investor_id)
    form = InvestorForm(request.POST or None, instance=investor)
    project_list = investor.project_set.all()
    return render(request, 'pages/investor_details.html', {"investor": investor, "form": form,"project": project,'project_list':project_list})
  • Related