Django:通过外键字段的ID查询的正确方法是什么? [英] Django: What is the correct way to query by foreign key field's id?

查看:40
本文介绍了Django:通过外键字段的ID查询的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 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)

现在,我想通过组织ID 过滤文件夹.所以我尝试了:

Now I want to filter the folder by organization id. so I tried:

  • 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))

相信与否,一切都会恢复原样.

Believe it or not everything returns the same.

所以有人知道通过外键字段的ID查询的正确方法是什么吗?

So anybody know what is the correct way to query by foreign key field's id?

但是当尝试通过以下方式创建文件夹时:

but when try to create folder by:

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')正常工作.

推荐答案

Django文档说,在大多数情况下,您应该使用 Folder.objects.filter(organization__pk = 1).

Django docs say that you should use Folder.objects.filter(organization__pk=1) in most cases.

这篇关于Django:通过外键字段的ID查询的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆