django使用外键加入

时间:2016-01-12 19:08:33

标签: python mysql django

我是django 2.7的新手。我试图使用外键约束运行连接查询。我有两个表table1和table2具有以下属性 - :

Model.py - :

class table1(models.Model):
    abcid = models.IntegerField(db_column='abcid', primary_key=True)  # Field name made lowercase.
    abcName = models.CharField(db_column='abcName', max_length=50, blank=True, null=True)  # Field name made lowercase.
    abcyear = models.IntegerField(db_column='abcYear', blank=True, null=True)



class table2(models.Model):
    abcid = models.ForeignKey('table1', models.DO_NOTHING, db_column='abcid')
    xyzname = models.CharField(db_column='xyzName', max_length=150, blank=True, null=True)  # Field name made lowercase.
    xyztype = models.CharField(db_column='xyzType', max_length=150, blank=True, null=True)  # Field name made lowercase.

我想获取xyzname包含菠萝'的所有记录。 我需要的列是 - abcid,abcname,abcyear,xyzname

到目前为止我所尝试的内容如下:

table1.objects.filter(table2__xyzname__icontains = 'pineapple')

table2.objects.filter(xyzname__icontains= 'pineapple').table1_set.all()

请帮助。 错误 - :

Request Method: GET
Request URL: http://127.0.0.1:8000/abc/trade/

Django Version: 1.9
Python Version: 2.7.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'abc_act']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/deep/workspace/src/abcNew/abc_journal/abcjournal/abcsoft/abc_act/views.py" in abcactname
  18.         data = serializers.serialize('json',abcactDS)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/core/serializers/__init__.py" in serialize
  129.     s.serialize(queryset, **options)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/core/serializers/base.py" in serialize
  79.         for count, obj in enumerate(queryset, start=1):

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
  258.         self._fetch_all()

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
  1074.             self._result_cache = list(self.iterator())

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
  52.         results = compiler.execute_sql()

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  852.             cursor.execute(sql, params)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  95.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  112.             return self.cursor.execute(query, args)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/MySQLdb/cursors.py" in execute
  205.             self.errorhandler(self, exc, value)

File "/home/deep/workspace/src/abcJournal/abcjournal/local/lib/python2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: OperationalError at /abc/trade/
Exception Value: (1054, "Unknown column 'table2.id' in 'field list'")

2 个答案:

答案 0 :(得分:1)

table2.objects.filter(xyzname__icontains='pineapple') \
              .select_related('abcid__abcid',
                              'abcid__abcName',
                              'abcid__abcyear')

select_related django doc

答案 1 :(得分:0)

在Django中,通常的方法是从一个模型返回一个对象的查询集,而不是包含多个模型中的字段的对象。

objects = table2.objects.filter(xyzname__icontains= 'pineapple')

然后,您可以遍历对象,并使用obj.abcid

跟随table2中的外键到table1
for obj in objects:
    print(obj.xyzname, obj.abcid.id, obj.abcid.abcName, obj.abcid.abcyear)

为了加快查询速度,您可以使用select_related(),以便Django进行内连接。

objects = table2.objects.filter(xyzname__icontains= 'pineapple').select_related('abcid')

这仍然返回table2对象的查询集。循环遍历它们并以与上面相同的方式访问外键。