2012-04-03 43 views
1

我在我的django應用程序中使用以下模型並希望跨多個字段進行查詢。我環顧了不同的地方,但無法找到我確切需要的東西。跨越多個模型的django訪問字段

class Attempt(models.Model, object): 
    '''Creates an Attempt Entity which is a subclass of models.Model class''' 
    attemptID_f = models.AutoField(primary_key=True) 
    questionID_f = models.ForeignKey(Question, verbose_name="Question", null=False) 
    userID_f = models.ForeignKey(User, verbose_name="User ID", null=False) 
    solution_f = models.TextField("Solution uploaded by the User", null=False) 
    errorReportID_f = models.ForeignKey(ErrorReport,verbose_name="Error Report for the Solution", null=True) 
    status_f = models.BooleanField("Status of attempt - true = right, false = wrong", blank=True, default=False) 
    timeOfSubmission_f = models.DateTimeField("Time of Submission", null=False) 
    compilerVersion_f = models.ForeignKey(CompilerVersion, verbose_name = "Compiler version of the Attempt",null=False) 

class Question(models.Model, object): 
    '''Creates the entity question 
    which is a subclass of models.Model''' 
    questionID_f = models.AutoField(primary_key=True) 
    questionText_f = models.TextField("Problem Statement", null=False) 
    questionTitle_f = models.CharField("Problem Title", max_length = 50, null = False) 
    level_f = models.ForeignKey(Level, verbose_name="Question Level", null=False) 
    type_f = models.ForeignKey(Type, verbose_name="Type of Question", null=False) 
    timeLimit_f = models.FloatField("Time Limit for Question",null=False) 

class Type(models.Model): 
    '''Creates the entity Type which is a subclass of models.Model class''' 
    typeID_f = models.AutoField(primary_key=True) 
    typeName_f = models.CharField("Type Name" , max_length = 30 , null = False) 

typesm = Attempt.objects.filter(userID_f = request.user).values('attempt__questionID_f__type_f__typeID_f') 

attempt__questionID_f__type_f__typeID_f如果我想引用類型模型的typeID_f領域的有效arguement,這是由問題模型type_f場,這是由嘗試模型questionID_f字段引用引用?

任何幫助,將不勝感激。

謝謝,

Pankaj。

+2

你試過了嗎?你試過的東西有問題嗎? – 2012-04-03 18:50:53

+0

從'models.Model,object'繼承什麼是?一個mixin只有在它添加了一些東西時纔有用,這是'object'無法定義的。 – 2012-04-03 18:54:39

+0

我真的希望「_f」在貴公司的風格指南中... – 2012-04-03 18:56:20

回答

1

應該是:

typesm = Attempt.objects.filter(userID_f = request.user).values('questionID_f__type_f__typeID_f') 

我不知道爲什麼你把attempt__前綴那裏當你正在查詢的Attempt模型。

參見:Lookups that span relationships

+0

謝謝。那樣做了! :) – 2012-04-12 22:00:07

0

我認爲,如果你使用的過濾器,然後類似你寫的東西應該工作正常

Attempt.objects.filter(questionID_f__type_f__typeID_f=42) 

要查找所有Attempt對象與類型42

如果你有一個嘗試實例attempt然後你想寫

if attempt.questionID_f.type_f.typeID_f == 42: 
    print "Answer found!" 

一些風格要點:

  • Django的使一個AutoField稱爲id默認
  • 無需從object
  • 繼承哇那些_f s爲醜!如果你需要db_column選項,你可以重新命名數據庫中的列名,如果你有一些SQL風格適合
  • 在你的幫助中不需要說which is a subclass of models.Model - 它確切地說在代碼和所有python文檔中系統知道
+0

我可以使用與values()函數調用的字符串參數相同的東西嗎? – 2012-04-03 19:33:45