[英]How do you get a query set of all models in a Django (1.2) ManyToMany relationship?
I have a Project model which has a pre-requisite attribute which is a ManyToMany field linking to other projects. 我有一个项目模型,该模型具有一个先决条件属性,该属性是一个链接到其他项目的ManyToMany字段。 That is, each project can have 0+ projects that must be completed before it can be completed. 也就是说,每个项目可以有0+个必须完成的项目,然后才能完成。
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. 但是project_a.prequisites
返回ManyRelatedManager
对象。 The special _set attribute doesn't seem to be working either: 特殊的_set属性似乎也不起作用:
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. 但是如果您知道我的意思,我宁愿以正确的方式做事。
project_a.prequisites.all()
Will return all Project
instances connected through your manytomanyfield 将返回通过您的manytomanyfield连接的所有Project
实例
a manager allows you to filter and get queryset objects as you would through the objects
property of your models 管理器允许您像通过模型的objects
属性那样过滤和获取queryset对象
this would allow you to do something like 这将允许您做类似的事情
project_a.prequisites.filter(title='a_prereq_title')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.