Django:通过外键字段的id查询的正确方法是什么?

时间:2015-04-16 11:04:12

标签: django django-models

我有两个models

class Organization(models.Model):
    title = models.CharField(max_length=100)

class Folder(models.Model):
    organization = models.ForeignKey("Organization",related_name='folders')
    title = models.CharField(max_length=50)

现在我要按folder过滤organization id。所以我试过了:

  • Folder.objects.filter(organization= 1)
  • Folder.objects.filter(organization_id= 1)
  • Folder.objects.filter(organization__id= 1)
  • Folder.objects.filter(organization__pk= 1)
  • Folder.objects.filter(organization= Organization.objects.get(id=1))

不管你信不信,一切都会回归。

所以任何人都知道外键字段ID的正确查询方式是什么?

更新

但是在尝试创建folder时:

Folder.objects.create(organization__id=1,title='hello')

得到错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/query.py", line 370, in create
    obj = self.model(**kwargs)
  File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/base.py", line 452, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'organization__id' is an invalid keyword argument for this function

但是Folder.objects.create(organization_id=1,title='hello')工作正常。

2 个答案:

答案 0 :(得分:3)

Django docs说你应该在大多数情况下使用Folder.objects.filter(organization__pk=1)

答案 1 :(得分:2)

回答更新:

可能Folder.objects.create(organization_id=1,title='hello')有效,因为Django appends "_id" to the field name to create its database column name