奇怪:为什么Django相关的很多查找都是这样工作的(但不像文档中的那样)?

2024-09-27 21:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

因此,要获取所有属于UserprojectNlpneutralfeature行,其中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怎么知道monitoringwordsrelated_name?没有错误对我来说很奇怪,因为在Nlpneutralfeature模型中没有monitoringwords字段!你知道吗


Tags: djangoname模型truemodelmodelsmaxmany
2条回答

注意Django docs中的短语:

The name to user for the relation from the related object back to this one. It's also the default value for related_query_name (the name to use for the reverse filter name from the target model).

在您的示例中,“目标模型”是Nlpneutralfeature。在ManyToManyField Userproject.monitoringwords上设置related_name = 'monitoringwords'时,它告诉Django使用该related_nameNlpneutralfeature模型对象向后引用相应的Userproject模型对象。你知道吗

相应地,如果您用related_name = 'foo'声明了Userproject.monitoringwords,那么查询属于项目48的所有Nlpneautralfeatures的方法将是:Nlpneautralfeature.objects.filter(foo__name='48')。你知道吗

这里的related_name可以让您获得与Nlpneutralfeature模型相关的用户项目模型。 例如:

nf = Nlpneutralfeature.objects.get(neutral_feature="XXX")
# From here you can get all Userprojects related to this nf like this:
userProjects = nf.monitoringwords.all()

如果您没有声明相关的名称,那么您必须这样做:

nf = Nlpneutralfeature.objects.get(neutral_feature="XXX")
# From here you can get all Userprojects related to this nf like this:
userProjects = nf.Userproject_set.all()

我想你对这个属性的理解是相反的。。我认为你应该在这里这样声明:related_name="user_projects"

总之,当您想从相关模型中获取当前模型(在其中声明M2M关系)时,可以使用related\u名称。你知道吗

相关问题 更多 >

    热门问题