【发布时间】:2017-10-31 18:11:35
【问题描述】:
我是 Django 的新手(使用过 1.11),我读过这篇文章(https://docs.djangoproject.com/fr/1.11/topics/db/models/),但我没有为我的问题找到明确的答案:如何检索对象
举个例子,假设我有以下模型:
class StudentCollaborator(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
code_postal = models.IntegerField()
collaborative_tool = models.BooleanField(default=False)
def get_skills(self):
return SkillHistory.objects.filter(student=self.user, value="acquired").values_list('skill')
技能历史:
class SkillHistory(models.Model):
"""
The reason why a Skill is acquired or not,
or not yet, when and by who/how
"""
skill = models.ForeignKey(Skill)
"""The Skill to validate"""
student = models.ForeignKey('users.Student')
"""The Student concerned by this Skill"""
datetime = models.DateTimeField(auto_now_add=True)
"""The date the Skill status was created"""
value = models.CharField(max_length=255, choices=(
('unknown', 'Inconnu'),
('acquired', 'Acquise'),
('not acquired', 'None Acquise'),
))
"""The Skill status : unknown, acquired or not acquired"""
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
reason_object = GenericForeignKey('content_type', 'object_id')
reason = models.CharField(max_length=255)
"""Why the Skill is validated or not"""
by_who = models.ForeignKey(User)
class Meta:
ordering = ['datetime']
最后是技能课:
class Skill(models.Model):
"""[FR] Compétence
A Skill can be evaluated through questions answered by a student.
Thus, when evaluated, a Skill can be acquired by a student, or not.
"""
code = models.CharField(max_length=20, unique=True, db_index=True)
"""The Skill reference code"""
name = models.CharField(max_length=255)
"""The Skill name"""
description = models.CharField(max_length=255)
如何在 get_skills 函数中检索技能对象(而不是其 ID);谢谢?
谢谢
【问题讨论】:
-
你可以使用类似
return SkillHistory.objects.filter(student=self.user, value="acquired").values('skill__code', 'skill__name', 'skill')
标签: django python-2.7 orm foreign-keys