我最近从Django 1.6升级到了Django 1.8。当我这样做时,我发现我不再能够通过外键关系进行查找,如下所述: https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships
设置系统,以便有两个项目使用相同的数据库。 (不是我的想法,而是我现在想要改变的东西。)最初创建和迁移模型的项目在升级后工作得很好,但另一个没有。每个模型文件都是相同的。
Models.py:
class Site(models.Model):
name = models.CharField(max_length=255)
class Meta:
app_label = 'project1'
class Page(models.Model):
title = models.CharField(max_length=255)
site = models.ForeignKey('Site')
class Meta:
app_label = 'project1'
Django Shell的错误回溯:
>>> x = models.Site.objects.filter(page__id=1000)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1314, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1342, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1154, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1035, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1401, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'page' into field. Choices are: name, id
在第一个项目中,相同的查询按预期工作:
>>> x = models.Site.objects.filter(page__id=1000)
[<Site: http://stackoverflow.com>]
答案 0 :(得分:6)
如果在`ForeignKey?
上设置related_name
怎么办?
class Page(models.Model):
site = models.ForeignKey('Site', related_name="pages") # Note the related_name here
我在另一个项目上尝试了它并且它起作用了:
>>> Site.objects.filter(pages__pk=42)
[<Site: http://stackoverflow.com>]
如果您未设置related_name
,我认为默认值为<model>_set
。所以它应该是page_set
。
答案 1 :(得分:1)
我是Django的新手,不知道这是否对您有帮助,但是我遇到了同样的问题。就我而言,这是输入错误。
我之前写过这篇文章:
Question.objects.filter(question_text_startswith ='What')
在Django文档中,我注意到在查找startswith
之前应该有2个下划线:
Question.objects.filter(question_text__startswith='What')