【问题标题】:Django : Retrieve objects from relationDjango:从关系中检索对象
【发布时间】: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


【解决方案1】:

您无法直接获取 Skill 对象。但是你可以通过这个查询获得技能属性。

SkillHistory.objects.filter(student=self.user, value="acquired").values('skill__name', 'skill__code')

【讨论】:

  • 我不知道:您的答案与我找到的 django 文档中丢失的示例相匹配 ...
  • @jy95 上面的答案正是 Django ORM 查询的完成方式。这也符合上面的例子。
【解决方案2】:
Skill.objects.filter(skillhistory_set__student=self.user, skillhistory_set__value="acquired")

使用相关名称过滤。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多