django访问跨多个模型的字段

时间:2012-04-03 18:44:29

标签: python django foreign-key-relationship html

我在我的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')

如果我想引用类型为MODEL的attempt__questionID_f__type_f__typeID_f字段,那么typeID_f是一个有效的争论吗?这个字段由问题模型的type_f字段引用,该字段由{{1}引用尝试模型领域?

任何帮助都将不胜感激。

谢谢,

的Pankaj。

2 个答案:

答案 0 :(得分:2)

应该是:

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

我不确定为什么在查询attempt__模型时将Attempt前缀放在那里。

请参阅:Lookups that span relationships

答案 1 :(得分:0)

我认为如果您使用过滤器,那么类似于您编写的内容应该可以正常工作

Attempt.objects.filter(questionID_f__type_f__typeID_f=42)

查找类型为42的所有Attempt个对象。

如果你有一个尝试实例attempt,那么你想写

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

一些风格点:

  • django默认情况下AutoField名为id
  • 无需继承object
  • 哇这些_f很难看!如果您想要使用db_column选项,则可以使用{{3}}选项重命名数据库中的列名称
  • 无需在您的帮助中说which is a subclass of models.Model - 它在代码中完全说明并且所有python文档系统都理解