Django访问ForeignKey模型对象 [英] Django accessing ForeignKey model objects

查看:79
本文介绍了Django访问ForeignKey模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说以下内容:

class Employee(models.Model):
    firstName = models.CharField(max_length = 30)
    lastName = models.CharField(max_length = 30)

class License(models.Model):
    employee = models.ForeignKey(Employee)
    type = models.CharField(max_length = 30)

在一个自定义管理命令中,我m用 employees = Employee.objects.all()提取所有Employee对象...如何为每个雇员对象访问关联的License对象?我已经看到有关为此目的使用ContentType的问题,但是我对它的实际用途感到困惑。谁能在这种情况下提供有关如何使用ContentType(或其他解决方案)的示例?

and in a custom management command, I'm pulling in all the Employee objects with employees = Employee.objects.all()... how can I access associated License objects for each employee object? I have seen questions that talk about using ContentType for this purpose, but I'm confused on it's practical use. Can anyone provide an example on how to use ContentType (or another solution) in this context?

推荐答案

employee.license_set.all()

https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-相关对象

这篇关于Django访问ForeignKey模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆