iT邦幫忙

0

Django連接MSSQL下ORM語法建立foreign key屬性資料出錯

各位前賢好,近期學習Django

連接MSSQL作為資料庫

但目前碰上一個問題懇請解惑:

Model.py

class Restaurant(models.Model):
    name = models.CharField(max_length=20)
    phone = models.CharField(max_length=15)

class Food(models.Model):
    name = models.CharField(max_length=20)
    restaurant = models.ForeignKey(Restaurant)

在Python shell下ORM語法建立資料:

from restaurant.models import Restaurant,Food
r = Restaurant.objects.create(name='吉意得餐廳',phone='02-123456')

這兩行都順利成功,但執行下列這行出錯:

f = Food.objects.create(name='炒青菜', restaurant = r)

→ 執行報錯:

The above exception was the direct cause of the following exception:

... py檔案細節錯誤 ...

django.db.utils.DatabaseError: (-2147352567, '發生例外狀況。', (0, 'Microsoft OLE DB Provider for SQL Server', '運算元類型衝突: ntext 與 decimal 不相容', None, 0, -2147217913), None)

錯誤有點多,但看起來好像SQL Server在插入foreign key資料時會產生錯誤


而如果依照此影片方式:https://youtu.be/1RkipG5YQO0?t=3m28s

DB改成SQL LITE,插入Foods的資料則不會出問題

語法應該是沒有錯才是~ 同樣語法在SQL LITE可以執行但MSSQL卻報錯

還是使用MSSQL作為資料庫,在python shell用ORM語法建立Foreign Key資料時,還需要設定什麼嗎~~?

先感謝各位解惑!!

froce iT邦大師 1 級 ‧ 2018-06-03 11:44:37 檢舉
直接用SSMS去看你Food資料表結構有沒有問題,因為沒用過MS SQL server做ORM,所以我也不清楚。

然後你連接SQL server的套件是?
你好~ 感謝回答

想請問有沒有問題是指什麼呢?

在SSMS看Food表中,restaurant外來鍵欄位是被設定成外來鍵沒有錯、建立檢視表:Food表的restaurant外來鍵也與Restaurant表的id相依

下SQL語法:

insert into [restaurant_food] ([name]
    ,[restaurant_id]) values ('宮保雞丁', 1)

也是順利追增資料的~


Django連接SQL Server的套件資料是:
django-mssql、pypiwin32

Django版本:1.8.1

Setting.py參考這篇:
https://dotblogs.com.tw/jojo/2015/10/30/153749
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
I code so I am
iT邦高手 1 級 ‧ 2018-06-03 16:31:33

應該是 restaurant = 1
f = Food.objects.create(name='炒青菜', restaurant = 1)

froce iT邦大師 1 級 ‧ 2018-06-03 18:43:48 檢舉

不對,Django的foreign key是指定物件沒錯。

你好~ 感謝回答

DB改為SQL LITE的話

使用Django中下ORM語法新增foreign key資料

f = Food.objects.create(name='炒青菜', restaurant = r)

是不會出錯的~ 僅有在連接MSSQL才會

若restaurant = 1則會出現以下錯誤:

ValueError: Cannot assign "1": "Food.restaurant" must be a "Restaurant" instance.

0
froce
iT邦大師 1 級 ‧ 2018-06-03 23:49:54

http://django-mssql.readthedocs.io/en/latest/settings.html#provider

use_mars = True doesn’t always work properly with ‘SQLOLEDB’ and can result in the error “Cannot create new connection because in manual or distributed transaction mode.” if you try to filter a queryset with another queryset.

試試看改 provider 成 SQLCLI11 試試看。
或是把 MARS Connection=True 移掉。

看更多先前的回應...收起先前的回應...

你好~

  1. provider 成 SQLCLI11
    Runserver會報錯顯示:找不到提供者

  2. MARS Connection=True移除
    Runserver不會出錯,但foreign key資料一樣無法新增 (錯誤同樣)

tenno081 iT邦研究生 4 級 ‧ 2018-06-04 12:22:40 檢舉

感謝,後來找到問題了

樓上 ... :O?

froce iT邦大師 1 級 ‧ 2018-06-04 18:43:00 檢舉

https://github.com/michiya/django-pyodbc-azure
或許你可以試試看,換成用odbc driver的跑跑看。

我要發表回答

立即登入回答