Question

I have a Project model which has a pre-requisite attribute which is a ManyToMany field linking to other projects. That is, each project can have 0+ projects that must be completed before it can be completed.

class Project(models.Model):
    title = models.CharField(max_length=200)
    prequisites = models.ManyToManyField('self', null=True, blank=True)

How do I return all projects that are prerequisite to this project? I want to do something like this:

project_a = Project.objects.get(title="My Cool Project")

for pre_requisite in project_a.prequisites:
    # do something with pre_requisite

but project_a.prequisites returns a ManyRelatedManager object. The special _set attribute doesn't seem to be working either:

project_a.prequisites_set
AttributeError: 'Project' object has no attribute 'prequisites_set'

I'm thinking about modelling the pre-requisites in another model:

class ProjectPrequisite(models.Model):
    project = models.ForeignKey(Project)
    prequisite = models.ForeignKey(Project)

but I'd rather do things the right way, if you know what I mean.

Was it helpful?

Solution

project_a.prequisites.all()

Will return all Project instances connected through your manytomanyfield

a manager allows you to filter and get queryset objects as you would through the objects property of your models

this would allow you to do something like

project_a.prequisites.filter(title='a_prereq_title')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top