Django文档描述了如何查询反向m2m字段: https://docs.djangoproject.com/en/1.8/topics/db/queries/#many-to-many-relationships
根据this answer,我们应该使用related_name
作为查询中的第一个参数。你知道吗
但我很难做到这一点。(我使用的是django1.8.5)。以下是我的示例模型:
class Nlpneutralfeature(models.Model):
neutral_feature = models.CharField(u'found word', max_length=255, default='')
class Userproject(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="project", verbose_name=("owner"))
monitoring_words = models.ManyToManyField(Nlpneutralfeature, null=True, blank=True, related_name="monitoringwords")
name = models.CharField(u'Название проекта', unique=True, max_length=255)
因此,要获取所有属于Userproject
的Nlpneutralfeature
行,其中Userproject.name == '48'
,我需要执行以下操作:
Nlpneutralfeature.objects.filter(userproject__monitoringwords__name='48')
但这行不通。我得到的错误是:Cannot resolve keyword *'userproject'* into field
。你知道吗
因此,Django无法理解'userproject'是小写的模型名userproject。你知道吗
现在,这起作用了:
Nlpneutralfeature.objects.filter(monitoringwords__name='48')
Django怎么知道monitoringwords
是related_name
?没有错误对我来说很奇怪,因为在Nlpneutralfeature
模型中没有monitoringwords
字段!你知道吗
注意Django docs中的短语:
在您的示例中,“目标模型”是
Nlpneutralfeature
。在ManyToManyFieldUserproject.monitoringwords
上设置related_name = 'monitoringwords'
时,它告诉Django使用该related_name
从Nlpneutralfeature
模型对象向后引用相应的Userproject
模型对象。你知道吗相应地,如果您用
related_name = 'foo'
声明了Userproject.monitoringwords
,那么查询属于项目48的所有Nlpneautralfeatures
的方法将是:Nlpneautralfeature.objects.filter(foo__name='48')
。你知道吗这里的
related_name
可以让您获得与Nlpneutralfeature
模型相关的用户项目模型。 例如:如果您没有声明相关的名称,那么您必须这样做:
我想你对这个属性的理解是相反的。。我认为你应该在这里这样声明:
related_name="user_projects"
总之,当您想从相关模型中获取当前模型(在其中声明M2M关系)时,可以使用related\u名称。你知道吗
相关问题 更多 >
编程相关推荐