2015-10-19 86 views
7

我爲多選題創建了一個模型。每個問題有5個選擇 的答案。我需要每個問題對象基於它的 問題和答案是唯一的。所以,我設計這樣的模型。有沒有辦法在django中用mysql db後端創建獨特的TextField?

from django.db import models 


class MultipleChoiceQuestion(models.Model): 
    ANSWERS = [('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e')] 
    question = models.TextField() 
    a = models.TextField() 
    b = models.TextField() 
    c = models.TextField() 
    d = models.TextField() 
    e = models.TextField() 
    true_answer = models.CharField(max_length=1, choices=ANSWERS) 

    class Meta: 
     unique_together = [('question', 'a', 'b', 'c', 'd', 'e')] 

當我運行migrate,MySQL的給這個錯誤:

1170, "BLOB/TEXT column 'question' used in key specification without a key length"

我發現這個錯誤已經討論here。但是,我不能使用 CharField以及它的小限制,因爲我需要存儲長文本 (直到10000個字符或更多)。

sqlite3和postgresql可以做到這一點(我的意思是django沒有抱怨關於TEXT的關鍵規範 )。

我需要使用mysql的原因,因爲我將部署這個服務器 django應用程序只提供MySQL,沒有postgresql。

那麼,無論如何,我可以做到這一點?

回答

1

它看起來像這是一個django/mysql錯誤,其中django blames MySql和「wontfix」它。他們的建議是將模型鑰匙關閉,並手動添加約束。巨大的黑客,但是,這可能是唯一的解決方案。但是,如果您的密鑰超過1000字節,您將需要重新編譯MySql。

The maximum key length is 1000 bytes. This can also be changed by changing the source and recompiling. For the case of a key longer than 250 bytes, a larger key block size than the default of 1024 bytes is used. From The Manual

我不建議,由於幾個原因,包括性能和周圍hackery。我建議您不要重新編譯,而是創建一個獨特的散列字段。這將創建一個所有字段的總和,總是32個字符。重複的機率是2^128中的1,所以你很安全。

from django.db import models 
import hashlib 


class MultipleChoiceQuestion(models.Model): 
    ANSWERS = [('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e')] 
    question = models.TextField() 
    a = models.TextField() 
    b = models.TextField() 
    c = models.TextField() 
    d = models.TextField() 
    e = models.TextField() 
    true_answer = models.CharField(max_length=1, choices=ANSWERS) 
    unique_hash = models.CharField(max_length=32, unique=True) 

    def save(self, *args, **kwargs): 
     m = hashlib.md5() 
     m.update(self.question) 
     m.update(self.a) 
     m.update(self.b) 
     m.update(self.c) 
     m.update(self.d) 
     m.update(self.e) 
     self.unique_hash = m.digest() 
     super(MultipleChoiceQuestion, self).save(*args, **kwargs) 
+0

所以很有幫助!謝謝 – fpghost

相關問題