2012-04-03 48 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