2016-01-12 85 views
1

我是新來的Django 2.7。我正嘗試使用外鍵約束運行連接查詢。我有兩個表Table 1和Table具有以下屬性 - :django加入使用外鍵

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'") 
+1

建議使用模型的大寫字母,例如'Table1'和'Table2'。這會讓您的問題更容易理解其他Django用戶。 – Alasdair

+0

下次還會照顧:) – Deep

回答

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

select_relateddjango doc

+0

我試過這個,但是得到一個錯誤-'abcid'沒有解析到支持預取的項目 – Deep

+0

我編輯了我的答案。你可以再試一次嗎? –

+0

同樣的錯誤和'table2s'它可以是任何事情或我必須寫它,因爲它是。 – Deep

0

在Django中,常規方法是從一個模型返回對象的查詢集,而不是包含來自多個模型的字段的對象。

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

然後,您可以遍歷的對象,並按照表2的外鍵表1與obj.abcid

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對象的查詢集。循環遍歷它們並以與上面相同的方式訪問外鍵。

+0

獲取錯誤長對象沒有屬性ID – Deep

+0

實際上它給錯誤的ID不abcid,即abcid.id它是指主表。我遇到同樣的問題,我不能使用外鍵引用來引用主字段 – Deep

+0

由於table1的主鍵是'abcid',它應該是'obj.abcid.abcid'。另一種選擇是使用'obj.abcid_id'。 – Alasdair